I'm new to this website and so far it really helped me just from looking.
I'm building and app that contains a playlist from youtube, so far it's working but I only have one video and the next video will only show if you press on the next button, I want to create a list of all videos on that playlist.
Currently using java for android and xml, would like to keep it that way if it's possible.
Thank you.
my code:
import android.drm.DrmStore;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayer.ErrorReason;
import com.google.android.youtube.player.YouTubePlayer.PlaybackEventListener;
import com.google.android.youtube.player.YouTubePlayer.PlayerStateChangeListener;
import com.google.android.youtube.player.YouTubePlayer.Provider;
import com.google.android.youtube.player.YouTubePlayerView;
import com.google.android.youtube.player.YouTubePlayer.OnFullscreenListener;
public class ky extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
public static final String API_KEY = "api";
//http://youtu.be/<VIDEO_ID>
public static final String VIDEO_ID = "PLZeI1YOvEK7EK499BrkBl95VseODbMDa-";
public void onFullscreen(boolean isFullscreen) {
if (isFullscreen)
playbackEventListener.onPlaying();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** attaching layout xml **/
setContentView(R.layout.ky);
/** Initializing YouTube player view **/
YouTubePlayerView youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_player);
youTubePlayerView.initialize(API_KEY, this);
}
#Override
public void onInitializationFailure(Provider provider, YouTubeInitializationResult result) {
Toast.makeText(this, "Failured to Initialize!", Toast.LENGTH_LONG).show();
}
#Override
public void onInitializationSuccess(Provider provider, final YouTubePlayer player, boolean wasRestored ) {
/** add listeners to YouTubePlayer instance **/
player.setPlayerStateChangeListener(playerStateChangeListener);
player.setPlaybackEventListener(playbackEventListener);
player.setOnFullscreenListener(new OnFullscreenListener() {
#Override
public void onFullscreen(boolean b) {
if(b)
player.play();
else
player.play();
}
});
/** Start buffering **/
if (!wasRestored) {
player.loadPlaylist(VIDEO_ID);
}
}
private PlaybackEventListener playbackEventListener = new PlaybackEventListener() {
#Override
public void onBuffering(boolean arg0) {
}
#Override
public void onPaused() {
}
#Override
public void onPlaying() {
}
#Override
public void onSeekTo(int arg0) {
}
#Override
public void onStopped() {
}
};
private PlayerStateChangeListener playerStateChangeListener = new PlayerStateChangeListener() {
#Override
public void onAdStarted() {
}
#Override
public void onError(ErrorReason arg0) {
}
#Override
public void onLoaded(String arg0) {
}
#Override
public void onLoading() {
}
#Override
public void onVideoEnded() {
}
#Override
public void onVideoStarted() {
}
};
}
xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:background="#color/black"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".example">
<TextView android:text="#string/hello_world" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtube_player"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/black"/>
</RelativeLayout>
I've done this using Youtube Api rest calls, async task and a recyclerview.
RecyclerView helps create a list and async task helps you make http requests in the background.
Look up the basics of async task and recyclerview. http://www.androidhive.info/ has great tutorials on this.
The Youtube rest call will look like this(I believe the max results are 50):
https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=iBi9LVIrC-fVelw2-I2r-yrEk6SpXfO8&key=AIzaSyCI1oCTXwZzgVv7LDQ8NykSIUEWt247KnU&maxResults=50
Here are some steps to get you started:
For example in this playlist url: https://www.youtube.com/watch?v=2q7XGuH2Q-s&list=PLuR1PJnGR-Igj4mNcr6_zDkQ3DTVA6wG5
Everything after "PL" is the id "uR1PJnGR-Igj4mNcr6_zDkQ3DTVA6wG5".
Also now you have to create a browser key in Google Developer console. You don't have to enter anything in the textbox, just click enter, and retrieve your api key
In your Google Developers console,under "APIs" make sure you turn Youtube Data api.
https://www.dropbox.com/s/6wtr7hpawx3ij64/youtubeApi.PNG
https://developers.google.com/youtube/android/player/downloads/
Add the jar file from the downloads to your libs folder in your newly downloaded project.DONT add it by dragging it into Android Studio
Next go to android studio and click the project drop down:
https://www.dropbox.com/s/cjlr4fnnikpnx7a/Screen%20Shot%202015-04-22%20at%2012.39.28%20PM.png?dl=0
then drop down the libs folder and you will see the youtube jar.right click the jar file and click “add as library”.
I have a more in-depth tutorial here:
http://cmcoffee91.com/blog/2016/12/18/how-to-add-youtube-playlist-to-your-android-app/
You can get everything with youtube data api, it's very easy and simple.
https://developers.google.com/youtube/v3/
visit youtube developer api website. There are several methods in the api which can help to retrieve playlists,channels,users profile etc.For reference to insert playlist
The other two answers are correct. Specifically, the YouTube API REST call you are looking for is under PlaylistItems, which gets a list of all videos in a playlist.
From the docs, the GET call is:
GET https://www.googleapis.com/youtube/v3/playlistItems?part=id&playlistId=[yourPlaylistId]
Related
I need to make a Controller for my player app. With the help of it user would play, pause, choose next or previous song. But this controller isn't shown and I don't know why?
I have already done method for setting data for controller and class for this controller.
Here's the code of the method:
private void setController(){
controller = new MusicController(this);
controller.setPrevNextListeners(new View.OnClickListener() {
#Override
public void onClick(View v) {
playNext();
}
}, new View.OnClickListener() {
#Override
public void onClick(View v) {
playPrev();
}
});
controller.setMediaPlayer(this);
controller.setAnchorView(findViewById(R.id.songList));
controller.setEnabled(true);
}
And here's the code of the class:
package asus.example.com.player;
import android.content.Context;
import android.widget.MediaController;
public class MusicController extends MediaController {
public MusicController(Context context) {
super(context);
}
public void hide(){}
}`
The show() method needs to be called for it to be shown on screen, when it's not created as part of an XML Layout. At the end of your setController() method, call this:
controller.show()
I play video in MainActivityand video is playig fine. While playing video, if I open the same activity another time and come back to previous MainActivity youtube progressbar keeps turning and nothing happens. I read the documentation and couldn't find anything related this problem. Indeed, the documentation is very old (updated in 2015), and YouTubeAndroidPlayerApi library was updated in 2017. Guide me to right direction.
MainActivity.java
public class MainActivity extends YouTubeBaseActivity
implements YouTubePlayer.OnInitializedListener {
private String YOUTUBE_API_KEY = "api_key";
private YouTubePlayerView youtubePlayerView;
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_main);
youtubePlayerView = findViewById(R.id.youtubePlayer);
youtubePlayerView.initialize(YOUTUBE_API_KEY, this);
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
Log.w("youtube_activity", "onInitialization success");
youTubePlayer.loadVideo("0KSOMA3QBU0");
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
Toast.makeText(this, "Initialization failure", Toast.LENGTH_SHORT);
}
public void onClick(View view) {
startActivity(new Intent(this, MainActivity.class));
}
}
layout xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtubePlayer"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</com.google.android.youtube.player.YouTubePlayerView>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:onClick="onClick"
android:text="Button" />
</LinearLayout>
Found solution with releasing YouTubePlayer when going to another youtubeplayeractivity. When came back to previous youtubeplayeractivity reninitialized YouTubePlayerView.
public void onClick(View view) {
youTubePlayer.release();
startActivity(new Intent(this, MainActivity.class));
}
#Override
protected void onRestart() {
super.onRestart();
youtubePlayerView.initialize(YOUTUBE_API_KEY, this);
}
I have a basic app for kids that allows them to click on icon to perform a youtube search (link to amazon app store).
Although I have done a lot of changes in the app, its removed from the Google Play store for "violation of the YouTube Terms of Service or YouTube API Terms of Service" (the full text is attached below).
I did a research here and it seems that my app dosen't have the problems that i have seen in other applications. the app dosen't have AD's and i think its not interfiring to the youtube Ad's and not playing videos in background.
In addition, I filed an appeal to Google Play. Their response was that my app streams copyrighted content from YouTube. I had a search for cartoons, so i removed it and resubmited and the app rejected again for the same reason.
when i asked for further assistance they answer: "Unfortunately, as much as we'd like to help, we aren't able to provide additional information for your inquiry".Very frustrating.
I'd appreciate your help. Perhaps i made a mistake in the code that implements the YoutubePlayer, Other ideas are welcome to.
the full Notification from Google Play:
This is a notification that your application, KidoTube, for package ID com.elelad.kidstube, has been removed from Google Play.
Please address the issue described below and submit a compliant update. Once approved, your application will again be available with all installs, ratings and reviews intact.
REASON FOR REMOVAL:Violation of section 4.4 of the Developer Distribution Agreement.
After a regular review, we have determined that your app downloads, monetizes, or otherwise accesses YouTube videos in violation of the YouTube Terms of Service or YouTube API Terms of Service. Accessing content, a product, or service in an unauthorized manner is a violation of the Developer Distribution Agreement, and is not allowed on Google Play.
All removals are tracked. Repeated removals will result in app suspension, at which point this app will count as a strike against the good standing of your developer account and no longer be available on Google Play.
This notification also serves as notice for other apps in your catalog. You can avoid future removals and/or app suspensions by immediately ensuring that no other apps in your catalog are in violation of (but not limited to) the above policy. Before publishing applications, please ensure your apps’ compliance with the Developer Distribution Agreement and Content Policy.
If you feel we have made this determination in error, you can visit this Google Play Help Center article.
The Google Play Team
My YoutubeActivity Class:
public class YoutubeActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
private final static String TAG = YoutubeActivity.class.getSimpleName();
YouTubePlayer player;
public static String YOUTUBE_VIDEO_ID = null;
LayoutInflater mLayoutInflater;
private FragmentActivity myContext;
public TextView textToast;
public View toastLayout;
ProgressBar cycleProgressBar;
Search search = new Search();
List<Video> mVideoList;
private static boolean initialize = false;
GetRandomInBackground getRandomInBackground;
YouTubePlayerView youTubePlayer;
ImageView waitLogo;
AnimationDrawable frameAnimation2;
ImageButton play;
public static void setYoutubeVideoId(String youtubeVideoId) {
YOUTUBE_VIDEO_ID = youtubeVideoId;
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);}
}
#Override
public void onCreate(Bundle savedInstanseState) {
super.onCreate(savedInstanseState);
ContentResolver mContentResolver = getContentResolver();
setContentView(R.layout.youtube_player);
waitLogo = (ImageView) findViewById(R.id.player_logo);
play = (ImageButton) findViewById(R.id.play);
try {
startLogoAnimation();
}catch (Exception e){
waitLogo.setImageResource(R.mipmap.kidotube);
}
youTubePlayer = (YouTubePlayerView) findViewById(R.id.vYouTubePlayer);
if (Setting.isStartRandomVideo()) {
getRandomInBackground = new GetRandomInBackground();
getRandomInBackground.execute();
}
youTubePlayer.initialize(Search.getGoogleApiKey(), this);
youTubePlayer.setVisibility(View.INVISIBLE);
}
#Override
protected void onPause() {
super.onPause();
BaseActivity.myLifecycleHandler.onActivityPaused(this);
}
#Override
protected void onResume() {
super.onResume();
BaseActivity.myLifecycleHandler.onActivityResumed(this);
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult result) {
Toast.makeText(this, "Cant initialize YouTube Player", Toast.LENGTH_LONG).show();
finish();
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer mplayer,
boolean wasRestored) {
this.player = mplayer;
player.setPlayerStyle(YouTubePlayer.PlayerStyle.CHROMELESS);
player.setPlayerStateChangeListener(playerStateChanageListener);
player.setPlaybackEventListener(playBackEvaentListener);
if (!Setting.isStartRandomVideo()) {
player.loadVideo(YOUTUBE_VIDEO_ID);
}
}
private YouTubePlayer.PlaybackEventListener playBackEvaentListener = new YouTubePlayer.PlaybackEventListener() {
public void onBuffering(boolean arg0) {
Log.v(TAG, "onBuffering");
}
#Override
public void onPaused() {
Log.v(TAG, "onPaused");
}
#Override
public void onPlaying() {
Log.v(TAG, "onPlaying");
}
#Override
public void onSeekTo(int arg0) {
Log.v(TAG, "onSeekTo");
}
#Override
public void onStopped() {
Log.v(TAG, "onStopped");
}
};
private YouTubePlayer.PlayerStateChangeListener playerStateChanageListener = new YouTubePlayer.PlayerStateChangeListener() {
#Override
public void onAdStarted() {
}
#Override
public void onError(YouTubePlayer.ErrorReason arg0) {
Log.v(TAG, "onError" );
Toast.makeText(YoutubeActivity.this, getString(R.string.Video_Error), Toast.LENGTH_LONG).show();
finish();
}
#Override
public void onLoaded(String arg0) {
Log.v(TAG, "onLoaded" + arg0);
}
#Override
public void onLoading() {
Log.v(TAG, "onLoading" );
}
#Override
public void onVideoEnded() {
Log.v(TAG, "onVideoEnded" );
finish();
}
#Override
public void onVideoStarted() {
Log.v(TAG, "onVideoStarted");
play.setVisibility(View.INVISIBLE);
waitLogo.setVisibility(View.INVISIBLE);
frameAnimation2.stop();
youTubePlayer.setVisibility(View.VISIBLE);
}
};
public class GetRandomInBackground extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
search.SearchNow(MainActivity.getSearchFor());
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
try {
if (search.getVideoList() == null || search.getVideoList().size() == 0) {
Toast.makeText(YoutubeActivity.this, getString(R.string.No_results_found), Toast.LENGTH_LONG).show();
Intent intent = new Intent(YoutubeActivity.this, MainActivity.class);
startActivity(intent);
} else {
mVideoList = search.getVideoList();
setYoutubeVideoId(search.playRand(mVideoList));
player.loadVideo(YOUTUBE_VIDEO_ID);
Search.setNumberOfVideosReturned(20);
}
}catch (Exception e){
finish();
}
}
}
public void startLogoAnimation(){
waitLogo.setBackgroundResource(R.drawable.wait_icon);
frameAnimation2 = (AnimationDrawable) waitLogo
.getBackground();
frameAnimation2.start();
}
public int animationDuration(AnimationDrawable animationDrawable){
int duration = 0;
int frames = animationDrawable.getNumberOfFrames();
for (int i = 0; i<frames; i++){
duration = duration + animationDrawable.getDuration(i);
}
return duration;
}
Thanks in advance!
well, it was one of my settings.
I made an option to click on icon and play a random video, apparently it's violation of the API terms.
When I removed the option the application is approved.
I hope this is the end..
I'm using the Youtube Android Player API as outlined here: https://developers.google.com/youtube/android/player/
However, I can't get more than one video into my activity at once. I tried simply putting two YouTubePlayerViews into the activity like so:
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin" >
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/view_one"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/view_two"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
MainActivity.java
package com.example.multidemo;
import android.os.Bundle;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayer.Provider;
import com.google.android.youtube.player.YouTubePlayerView;
public class MainActivity extends YouTubeBaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((YouTubePlayerView) findViewById(R.id.view_one)).initialize("API key", new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(Provider arg0, YouTubePlayer arg1, boolean arg2) {
arg1.cueVideo("RpwoN_XlN6Y");
}
#Override
public void onInitializationFailure(Provider arg0, YouTubeInitializationResult arg1) {
}
});
((YouTubePlayerView) findViewById(R.id.view_two)).initialize("API key", new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(Provider arg0, YouTubePlayer arg1, boolean arg2) {
arg1.cueVideo("jkk2mMq2x8E");
}
#Override
public void onInitializationFailure(Provider arg0, YouTubeInitializationResult arg1) {
}
});
}
}
When I try this, the first view just comes up black, while the second video loads. If I comment out the code in onCreate() for the second video, then just the first video will load.
Is there any way to get multiple YouTubePlayerViews into the same activity?
This might be too late for an answer, but i had the same issue recently. Hope this helps to someone who might face the same issue. The trick to get around this is Using YoutubePlayerFragments instead. As long as you use Youtube player view, you'll hit the limit imposed of only one initialization done out of multiple requests. Typically the initialization succeeds for last one.
I ended up dynamically generating gridlayout and placing my (dynamically generated)fragment's view in each of the cells. And then i initialize the instance of player inside onResume. Once initialization is sucessful, you'll get a handle to player, and you can cue different videos randomly on fragments.
I'll just paste the code that will give you an idea about how i am constructing fragments and doing initialization:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
mLogger.i("Preparing Youtube view for fragment ..");
mFragmentHeight = CustomFragment.getFragmentHeight(mNumScreens,mNumColumns);
mFragmentWidth = CustomFragment.getFragmentWidth(mNumColumns);
LinearLayout linearLayout = new LinearLayout(getActivity());
GridLayout.LayoutParams gridparams = new GridLayout.LayoutParams();
gridparams.rowSpec = GridLayout.spec(mGridRow);
gridparams.columnSpec = GridLayout.spec(mGridColumn);
gridparams.height = mFragmentHeight;
gridparams.width = mFragmentWidth;
linearLayout.setLayoutParams(gridparams);
if(YouTubeApiServiceUtil.isYouTubeApiServiceAvailable(getActivity())==
YouTubeInitializationResult.SUCCESS)
{
View ytView = super.onCreateView(inflater, container, savedInstanceState);
linearLayout.addView(ytView);
}
else
mLogger.e("Either youtube service is down," +
" or you dont have required version of YouTube app .." +
"\nYouTube Fragment will not work as expected..");
mView = linearLayout;
mLogger.i("Preparation youtube view for fragment complete..");
return mView;
}
#Override
public void onInitializationFailure(Provider arg0,
YouTubeInitializationResult arg1)
{
mLogger.e("Youtube player initialization failed");
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player,
boolean wasRestored)
{
mLogger.i("You tube player initialized successfully.. will attempt to stream..");
mYoutubePlayer = player;
setListeners();
try
{
if (!wasRestored)
{
if(mPlayListFragment)
player.loadPlaylist(getResourceID());
else
player.loadVideo(getResourceID());
}
}
catch(Exception e)
{
mLogger.e("Error loading playlist/video .."+e);
}
}
public void onResume()
{
super.onResume();
initialize(API_KEY, this);
}
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.
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!
Step1 : Follow Answer 16 by Nhano
Step2 : add below line in your Menifest YoutubeActivity tag.
android:configChanges="orientation|screenSize"
this solution worked for me..
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;
}