Android: When watching a youtube video fullscreen I press back and the Activity finish
Asked Answered
N

3

14

I've read all around the way of leaving fullscreen from a YouTube video is by pressing back, but in my Activity it's not working like this but I'd like it to.

I post you the code:

public class MainActivity extends YouTubeFailureRecoveryActivity {
    public static String prefix = "https://gdata.youtube.com/feeds/api/playlists/";
    public static String sufix = "?v=2&alt=jsonc";

    private String myPlayList = "PLZGKlf2ZwY7ua0C2oeUaXQKeLKNGy3mkh";

    private VideosListFragment videosFragment;

    // The next video to play
    private Video actualVideo;

    // This is the handler that receives the response when the YouTube read
    private Handler responseHandler;


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        videosFragment = (VideosListFragment) getFragmentManager().findFragmentById(R.id.videosListView);
        getUserYouTubeFeed();

    }

    @Override
    public void onInitializationSuccess(YouTubePlayer.Provider provider,
            YouTubePlayer player, boolean wasRestored) {
        if (!wasRestored) {
            player.loadVideo(actualVideo.getVideoId());
        }
    }

    @Override
    protected YouTubePlayer.Provider getYouTubePlayerProvider() {
        return (YouTubePlayerFragment) getFragmentManager().findFragmentById(
                R.id.youtube_fragment);
    }

    public void getUserYouTubeFeed() {
        responseHandler = new Handler() {
            public void handleMessage(Message msg) {
                populateListWithVideos(msg);
            };
        };
        // We start a new AsyncTask that does its work on its own thread
        // We pass in a handler that will be called when the task has finished
        LoadPlayListElements bgTask = new LoadPlayListElements(responseHandler);
        bgTask.execute(myPlayList);

    }

    /**
     * This method retrieves the Library of videos from the task and passes them
     * to our ListView
     * 
     * @param msg
     */
    private void populateListWithVideos(Message msg) {
        Library lib = (Library) msg.getData().get(
                LoadPlayListElements.LIBRARY);
        VideosAdapter videos = new VideosAdapter(this, lib.getVideos());
        videosFragment.setListAdapter(videos);
    }

    @Override
    protected void onStop() {
        // Make sure we null our handler when the activity has stopped
        responseHandler = null;
        super.onStop();
    }

    public void setVideo(Video _item, boolean _activate) {
        actualVideo = _item;
        if (_activate){
            YouTubePlayerFragment fragment = (YouTubePlayerFragment) getFragmentManager()
                    .findFragmentById(R.id.youtube_fragment);
            if (fragment != null && fragment.isInLayout()) {
                fragment.initialize(DeveloperKey.DEVELOPER_KEY, this);
            }
        }
    }
}

and the layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin" >

    <fragment
        android:id="@+id/videosListView"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:layout_marginTop="?android:attr/actionBarSize"
        class="com.vivoenmimundo.sc2hotsepicreplays.ui.phone.fragment.VideosListFragment" >
    </fragment>

    <fragment
      android:name="com.google.android.youtube.player.YouTubePlayerFragment"
      android:id="@+id/youtube_fragment"
      android:layout_width="0dp"
      android:layout_height="wrap_content"
      android:layout_weight="2"
      android:layout_gravity="center_vertical"/>
</LinearLayout>

Any idea? I've tried to not do anything too strange, just copy/paste from YouTube's API examples.

Needle answered 28/3, 2013 at 19:36 Comment(1)
It looks like a correct behavior that when you press back, the onStop or onDestory is called and the activity is destroyed. developer.android.com/training/basics/activity-lifecycle/…Iliad
N
31

It was, as said before, the correct behaviour - because the player was inside a fragment, I had to catch the back button with:

@Override
public void onBackPressed() {
    if (fullScreen){
        videoPlayer.setFullscreen(false);
    } else{
        super.onBackPressed();
    }
}

and set my "fullScreen" boolean like this:

@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider,
        YouTubePlayer player, boolean wasRestored) {
    if (!wasRestored) {
        showPlayer();
        videoPlayer = player;
        videoPlayer.setOnFullscreenListener(new OnFullscreenListener() {

            @Override
            public void onFullscreen(boolean _isFullScreen) {
                fullScreen = _isFullScreen;
            }
        });
        videoPlayer.loadVideo(actualVideo.getVideoId());
    }
}

thanks all!

Needle answered 31/3, 2013 at 19:28 Comment(3)
how do you access videoPlayer in your onBackPressed method? I tried the same but am getting this NullPointerException: Attempt to invoke interface method 'void com.google.android.youtube.player.YouTubePlayer.setFullscreen(boolean)' on a null object referenceTaima
put videoplayer object in a field variable inside onInitializationSuccess methodQuark
This wont work in fragment. As onBackPressed method is not available in fragment.Etna
P
3

Step1 : Follow Answer 16 by Nhano

Step2 : add below line in your Menifest YoutubeActivity tag.

android:configChanges="orientation|screenSize"

this solution worked for me..

Paleogeography answered 26/4, 2017 at 12:46 Comment(0)
C
0

You could try to detect the back button press and custom define what it does.

// Sets functionality of the hard buttons on the device
@Override 
public boolean onKeyUp(int keyCode, KeyEvent event)
{
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        // Custom define what you want to happen
    }
    return true;
}
Crystalcrystalline answered 28/3, 2013 at 20:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.