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);
}
Related
I am trying to initialize youtubeplayer fragment within a fragment. I successfully implemented the fragment within an activity but getting problem to initialize it in a fragment.
the code snippet for activity is as below
public class MainActivity extends AppCompatActivity {
private YouTubePlayerSupportFragmentX youTubePlayerFragment;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeYoutubePlayer();
private void initializeYoutubePlayer() {
youTubePlayerFragment = (YouTubePlayerSupportFragmentX) getSupportFragmentManager().findFragmentById(R.id.youtube_player_fragment);
if (youTubePlayerFragment == null)
return;
youTubePlayerFragment.initialize(Constants.DEVELOPER_KEY, new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player,
boolean wasRestored) {
if (!wasRestored) {
youTubePlayer = player;
//set the player style default
youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
//cue the 1st video by default
youTubePlayer.cueVideo(youtubeVideoArrayList.get(0));
youTubePlayer.addFullscreenControlFlag(YouTubePlayer.FULLSCREEN_FLAG_ALWAYS_FULLSCREEN_IN_LANDSCAPE);
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider arg0, YouTubeInitializationResult arg1) {
//print or show error if initialization failed
Log.e(TAG, "Youtube Player View initialization failed");
}
});
}
To convert this code into fragment, I tried this
public class Welcome extends Fragment {
private YouTubePlayerSupportFragmentX youTubePlayerFragment;
private YouTubePlayer youTubePlayer;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_welcome, container, false);
initializeYoutubePlayer();
private void initializeYoutubePlayer() {
youTubePlayerFragment = (YouTubePlayerSupportFragmentX) getSupportFragmentManager().findFragmentById(R.id.youtube_player_fragment);
if (youTubePlayerFragment == null)
return;
youTubePlayerFragment.initialize(Constants.DEVELOPER_KEY, new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
youTubePlayer = player;
//set the player style default
youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
//cue the 1st video by default
youTubePlayer.cueVideo(youtubeVideoArrayList.get(0));
youTubePlayer.addFullscreenControlFlag(YouTubePlayer.FULLSCREEN_FLAG_ALWAYS_FULLSCREEN_IN_LANDSCAPE);
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
Log.e(TAG, "Youtube Player View initialization failed");
}
});
}
private void getSupportFragmentManager() {
}
}
but getting error in finding the fragment layout. Can somebody guide me how to do this in fragment? The layout for Welcome fragment is as follows
<RelativeLayout 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:background="#FCFDFF"
tools:context="com.currentmedia.channelslayout.Welcome">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="32dp"
android:layout_alignParentTop="true"
android:layout_marginTop="0dp"
android:background="#FF0000"
app:title="Punjabi News Live"
app:titleTextColor="#FFFFFF" />
<!-- Youtube Player Fragment -->
<LinearLayout
android:id="#+id/linearlayout01"
android:layout_width="fill_parent"
android:layout_height="220dp"
android:layout_below="#id/adView"
android:layout_marginTop="2dp"
android:background="#ccc"
android:orientation="vertical">
<fragment
android:id="#+id/youtube_player_fragment"
android:name="com.google.android.youtube.player.YouTubePlayerSupportFragmentX"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
In your layout, instead of using a < fragment > you should use a < FragmentContainerView > and replace the fragment in your activity using transaction.
Here is a tutorial if you're new with manipulating fragment in 2020:
FragmentContainerView explanation
I want to implement YouTube Player View on my app, but since my app is an alarm clock, i don't want the user to be able to pause/stop the video or to change the volume. I tried to put a view on the YouTube Player View to block the clicks on it, but i guess that it's against the google policy because when i do that the video is not playing. I also tried:
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/ypvAlert"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="#dimen/half_activity_vertical_margin"
android:layout_marginBottom="#dimen/standard_button_size"
android:clickable="false" />
But it's not working. Is there something i can do?
With this solution, you can disable click events on a view and all its children by setting enable to false with view.setEnabled(false) for each child. Call it in onInitializationSuccess callback :
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider,
YouTubePlayer youTubePlayer, boolean b) {
enableDisableView(mYoutubeplayerView, false);
mPlayer = youTubePlayer;
mPlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.MINIMAL);
mPlayer.loadVideo("63kmMcHBQlA");
}
Here is a complete working example :
public class MainActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
String mApiKey = "YOUR_API_KEY";
YouTubePlayerView mYoutubeplayerView;
YouTubePlayer mPlayer;
/**
* disable all click event : https://stackoverflow.com/a/19464718/2614364 by Parag Chauhan
*
* #param view
* #param enabled
*/
public static void enableDisableView(View view, boolean enabled) {
view.setEnabled(enabled);
if (view instanceof ViewGroup) {
ViewGroup group = (ViewGroup) view;
for (int idx = 0; idx < group.getChildCount(); idx++) {
enableDisableView(group.getChildAt(idx), enabled);
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mYoutubeplayerView = (YouTubePlayerView) findViewById(R.id.ypvAlert);
mYoutubeplayerView.initialize(mApiKey, this);
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider,
YouTubePlayer youTubePlayer, boolean b) {
enableDisableView(mYoutubeplayerView, false);
mPlayer = youTubePlayer;
mPlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.MINIMAL);
mPlayer.loadVideo("63kmMcHBQlA");
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult youTubeInitializationResult) {
}
#Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
if (resultCode == RESULT_OK) {
mPlayer.release();
}
}
}
just add this line
youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.MINIMAL);
What i created while making CHROMELESS youtube player view is here. It is loading and playing perfectly but the buffering circle plays continuously even when video gets completed. Can anyone help me to remove buffering progress when it is not required and make a perfect youtube player?
MainActivity.java
package com.rocky.youtubedemo;
import android.content.Context;
import android.content.Intent;
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.YouTubePlayerView;
public class MainActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
private static final int RECOVERY_REQUEST = 1;
private static String YOUTUBE_API_KEY = "";
private YouTubePlayerView youTubeView;
private Context context;
private MyPlayerStateChangeListener playerStateChangeListener;
private MyPlaybackEventListener playbackEventListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
playerStateChangeListener = new MyPlayerStateChangeListener();
playbackEventListener = new MyPlaybackEventListener();
YOUTUBE_API_KEY = "PLACE_YOUR_API_KEY_HERE";
youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
youTubeView.initialize(YOUTUBE_API_KEY, this);
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, final YouTubePlayer player, boolean wasRestored) {
player.setPlayerStateChangeListener(playerStateChangeListener);
player.setPlaybackEventListener(playbackEventListener);
if (!wasRestored) {
player.loadVideo("fhWaJi1Hsfo"); // Plays https://www.youtube.com/watch?v=fhWaJi1Hsfo
player.setPlayerStyle(YouTubePlayer.PlayerStyle.CHROMELESS);
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
Toast.makeText(context, errorReason.toString(), Toast.LENGTH_LONG).show();
// errorReason.getErrorDialog(this, RECOVERY_REQUEST).show();
} else {
String error = errorReason.toString();
Toast.makeText(context, error, Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_REQUEST) {
// Retry initialization if user performed a recovery action
getYouTubePlayerProvider().initialize(YOUTUBE_API_KEY, this);
}
}
private void showMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
protected YouTubePlayer.Provider getYouTubePlayerProvider() {
return youTubeView;
}
private final class MyPlaybackEventListener implements YouTubePlayer.PlaybackEventListener {
#Override
public void onPlaying() {
// Called when playback starts, either due to user action or call to play().
showMessage("Playing");
}
#Override
public void onPaused() {
// Called when playback is paused, either due to user action or call to pause().
showMessage("Paused");
}
#Override
public void onStopped() {
// Called when playback stops for a reason other than being paused.
showMessage("Stopped");
}
#Override
public void onBuffering(boolean b) {
showMessage("buffer");
}
#Override
public void onSeekTo(int i) {
// Called when a jump in playback position occurs, either
// due to user scrubbing or call to seekRelativeMillis() or seekToMillis()
}
}
private final class MyPlayerStateChangeListener implements YouTubePlayer.PlayerStateChangeListener {
#Override
public void onLoading() {
showMessage("loading");
}
#Override
public void onLoaded(String s) {
showMessage("loaded");
}
#Override
public void onAdStarted() {
// Called when playback of an advertisement starts.
}
#Override
public void onVideoStarted() {
// Called when playback of the video starts.
showMessage("started");
}
#Override
public void onVideoEnded() {
// Called when the video reaches its end.
}
#Override
public void onError(YouTubePlayer.ErrorReason errorReason) {
// Called when an error occurs.
}
}
}
activity_main.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"
tools:context=".MainActivity">
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtube_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
In your onInitializationSuccess(), set a PlaybackEventListener on the player. Override the onBuffering() and do something like this:
ViewGroup ytView = youTubeView; // if you are using YouTubePlayerView
ViewGroup ytView = (ViewGroup)ytPlayerFragment.getView(); // if you are using YouTubePlayerFragment
ProgressBar progressBar;
try {
// As of 2016-02-16, the ProgressBar is at position 0 -> 3 -> 2 in the view tree of the Youtube Player Fragment/View
ViewGroup child1 = (ViewGroup)ytView.getChildAt(0);
ViewGroup child2 = (ViewGroup)child1.getChildAt(3);
progressBar = (ProgressBar)child2.getChildAt(2);
} catch (Throwable t) {
// As its position may change, we fallback to looking for it
progressBar = findProgressBar(ytView);
// I recommend reporting this problem so that you can update the code in the try branch: direct access is more efficient than searching for it
}
int visibility = isBuffering ? View.VISIBLE : View.INVISIBLE;
if (progressBar != null) {
progressBar.setVisibility(visibility);
// Note that you could store the ProgressBar instance somewhere from here, and use that later instead of accessing it again.
}
Make method like this one:
private ProgressBar findProgressBar(View view) {
if (view instanceof ProgressBar) {
return (ProgressBar)view;
} else if (view instanceof ViewGroup) {
ViewGroup viewGroup = (ViewGroup)view;
for (int i = 0; i < viewGroup.getChildCount(); i++) {
ProgressBar res = findProgressBar(viewGroup.getChildAt(i));
if (res != null) return res;
}
}
return null
}
By this way you can enable progress when it is buffering and disable it when it is not.
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]
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;
}