I am try to play video using youtube video API
When I put static ID means declare ID in file at that time code is working.
But when I try to fetch ID from getIntent() I also got ID but video not play.
I got There was problem with network.
Below is my code. Its working in this condition.
this is Video_Activity.java
public class Video_Activity extends AppCompatActivity implements YouTubePlayer.OnInitializedListener {
TextView textView1, textView2;
ScrollView scrollView;
WebView webView;
VideoView videoView;
private MediaController mController;
private Uri uriYouTube;
private YouTubePlayerView youTubeView;
private static final int RECOVERY_DIALOG_REQUEST = 1;
Video video;
public String videourl;
// Google Console APIs developer key
// Replace this key with your's
String YOUTUBE_VIDEO_CODE;
String DEVELOPER_KEY;
//String Video_ids;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_);
DEVELOPER_KEY = "AIzaSyC0rjDLc0jkYY0Z66QgOnkNmkOAyOqpqnI";
// YouTube video id
YOUTUBE_VIDEO_CODE = "yExScIwJftE";
getSupportActionBar().setTitle(Html.fromHtml("<font color='#fdfafa'> Video View </font>"));
final Drawable upArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
getSupportActionBar().setHomeAsUpIndicator(upArrow);
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
YouTubePlayerSupportFragment frag = (YouTubePlayerSupportFragment) getSupportFragmentManager().findFragmentById(R.id.youtube_view);
if (frag == null) {
frag = YouTubePlayerSupportFragment.newInstance();
getSupportFragmentManager().beginTransaction().add(R.id.youtube_view, frag).commit();
}
frag.initialize(DEVELOPER_KEY, this);
Intent intent = getIntent();
if (null != intent) {
String Video_Title = intent.getStringExtra("Video_title");
String Video_Desc = intent.getStringExtra("Vide_desc");
//Video_ids = intent.getStringExtra("Video_ID");
//Log.i("Video_Url", " " + YouTube_VideoPlayer);
textView1 = (TextView) findViewById(R.id.activity_video_Title);
textView1.setText(Video_Title);
textView2 = (TextView) findViewById(R.id.activity_video_desc);
textView2.setText(Video_Desc);
scrollView = (ScrollView) findViewById(R.id.Scroller_Id_video);
scrollView.post(new Runnable() {
#Override
public void run() {
scrollView.smoothScrollTo(0, textView2.getBottom());
}
});
}
}
#Override
public void onInitializationFailure (YouTubePlayer.Provider provider,YouTubeInitializationResult errorReason){
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
}
else
{
//String YouTube_VidePlayer = getIntent().getStringExtra("Video_Player");
String YouTube_VideoPlayer = String.format(getString(R.string.error_player), errorReason.toString());
Toast.makeText(this, YouTube_VideoPlayer, Toast.LENGTH_LONG).show();
}
}
#Override
public void onInitializationSuccess (YouTubePlayer.Provider provider,YouTubePlayer player,boolean wasRestored){
if (!wasRestored) {
// loadVideo() will auto play video
// Use cueVideo() method, if you don't want to play it automatically
player.cueVideo(YOUTUBE_VIDEO_CODE);
//player.cueVideo(Video_ids);
// Hiding player controls
//player.setPlayerStyle(YouTubePlayer.PlayerStyle.CHROMELESS);
}
}
#Override
protected void onActivityResult ( int requestCode, int resultCode, Intent data){
if (requestCode == RECOVERY_DIALOG_REQUEST) {
// Retry initialization if user performed a recovery action
getYouTubePlayerProvider().initialize(Video_Config.DEVELOPER_KEY, this);
}
}
private YouTubePlayer.Provider getYouTubePlayerProvider() {
return (YouTubePlayerView) findViewById(R.id.youtube_view);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home){
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
Now when i Used
public class Video_Activity extends AppCompatActivity implements YouTubePlayer.OnInitializedListener {
TextView textView1, textView2;
ScrollView scrollView;
WebView webView;
VideoView videoView;
private MediaController mController;
private Uri uriYouTube;
private YouTubePlayerView youTubeView;
private static final int RECOVERY_DIALOG_REQUEST = 1;
Video video;
public String videourl;
// Google Console APIs developer key
// Replace this key with your's
public static final String DEVELOPER_KEY = "AIzaSyC0rjDLc0jkYY0Z66QgOnkNmkOAyOqpqnI";
// YouTube video id
//public static final String YOUTUBE_VIDEO_CODE = "yExScIwJftE";
String Video_ids;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_);
getSupportActionBar().setTitle(Html.fromHtml("<font color='#fdfafa'> Video View </font>"));
final Drawable upArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
getSupportActionBar().setHomeAsUpIndicator(upArrow);
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
YouTubePlayerSupportFragment frag = (YouTubePlayerSupportFragment) getSupportFragmentManager().findFragmentById(R.id.youtube_view);
if (frag == null) {
frag = YouTubePlayerSupportFragment.newInstance();
getSupportFragmentManager().beginTransaction().add(R.id.youtube_view, frag).commit();
}
frag.initialize(DEVELOPER_KEY, this);
Intent intent = getIntent();
if (null != intent) {
String Video_Title = intent.getStringExtra("Video_title");
String Video_Desc = intent.getStringExtra("Vide_desc");
Video_ids = intent.getStringExtra("Video_ID");
//Log.i("Video_Url", " " + YouTube_VideoPlayer);
textView1 = (TextView) findViewById(R.id.activity_video_Title);
textView1.setText(Video_Title);
textView2 = (TextView) findViewById(R.id.activity_video_desc);
textView2.setText(Video_Desc);
scrollView = (ScrollView) findViewById(R.id.Scroller_Id_video);
scrollView.post(new Runnable() {
#Override
public void run() {
scrollView.smoothScrollTo(0, textView2.getBottom());
}
});
}
}
#Override
public void onInitializationFailure (YouTubePlayer.Provider provider,YouTubeInitializationResult errorReason){
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
}
else
{
//String YouTube_VidePlayer = getIntent().getStringExtra("Video_Player");
String YouTube_VideoPlayer = String.format(getString(R.string.error_player), errorReason.toString());
Toast.makeText(this, YouTube_VideoPlayer, Toast.LENGTH_LONG).show();
}
}
#Override
public void onInitializationSuccess (YouTubePlayer.Provider provider,YouTubePlayer player,boolean wasRestored){
if (!wasRestored) {
// loadVideo() will auto play video
// Use cueVideo() method, if you don't want to play it automatically
//player.cueVideo(YouTube_VideoPlayer);
player.cueVideo(Video_ids);
// Hiding player controls
//player.setPlayerStyle(YouTubePlayer.PlayerStyle.CHROMELESS);
}
}
#Override
protected void onActivityResult ( int requestCode, int resultCode, Intent data){
if (requestCode == RECOVERY_DIALOG_REQUEST) {
// Retry initialization if user performed a recovery action
getYouTubePlayerProvider().initialize(Video_Config.DEVELOPER_KEY, this);
}
}
private YouTubePlayer.Provider getYouTubePlayerProvider() {
return (YouTubePlayerView) findViewById(R.id.youtube_view);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home){
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
YouTube id extraction is actually a different question but since this can solve your problem I am answering this. I usually do like this and it's working.
public void String getYoutubeId(String ytUrl)
{
String youtubeID ="";
if (ytUrl.contains("://youtu.be/")){
youtubeID=ytUrl.substring(ytUrl.lastIndexOf("/") + 1);
ytUrl="http://youtube.com/watch?v=" + youtubeID;
}else if (ytUrl.contains("watch?v=")){
if (ytUrl.contains("&")){
ytUrl=ytUrl.substring(0, ytUrl.indexOf('&'));
}
if (ytUrl.contains("https")){
ytUrl.replace("https", "http");
}
youtubeID=ytUrl.substring(ytUrl.indexOf("watch?v=") + 8);
}
return youtubeID;
}
Call getYoutubeId(youtube url) to get youtube id. Also print the id and compare it with the url you are passing and see if both matches.
Related
Hi facing issue in YouTubeAndroidPlayerAPI, here is the error i'm facing
W/YouTubeAndroidPlayerAPI: Forcefully created overlay:acqm#cada64
helper:Lazy#241a4cd view:null status: ....... {...}
NOTE - i have two activity class if user enter FirstActivity video is working fine. If user change activity from FirstActivity to SecondActivity in SecondActivity also video working fine, if user using system back button navigate to FirstActivity video not playing continuously loading happening but video not playing.(Added image for reference)
loading same Activity if user clicking button like this(FirstActivity and SecondActivity are same in my case, just for under standing purpose explained two activityes)
Intent intent = new Intent(YoutubeVideoPlay.this, YoutubeVideoPlay.class);
startActivity(intent);
Here is the code sample i'm using
FirstActivity.java
public class FirstActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
public static final String DEVELOPER_KEY = "xxxxxxxxxxxxxxxxxxx";
private static final int RECOVERY_DIALOG_REQUEST = 1;
private String url = "xxxxxxxxxxxxxxxxxxxx";
private String VIDEO_ID;
private YouTubePlayerFragment myYouTubePlayerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_youtube);
myYouTubePlayerFragment = (YouTubePlayerFragment) getFragmentManager().findFragmentById(R.id.youtubeplayerfragment);
myYouTubePlayerFragment.initialize(DEVELOPER_KEY, this);
VIDEO_ID = getYoutubeVideoId(url);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(FirstActivity .this, FirstActivity .class);
startActivity(intent);
}
});
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
} else {
String errorMessage = String.format("There was an error initializing the YouTubePlayer (%1$s)",
errorReason.toString());
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
player.cueVideo(VIDEO_ID);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_DIALOG_REQUEST) {
// Retry initialization if user performed a recovery action
getYouTubePlayerProvider().initialize(DEVELOPER_KEY, this);
}
}
protected YouTubePlayer.Provider getYouTubePlayerProvider() {
return (YouTubePlayerView) findViewById(R.id.youtubeplayerfragment);
}
public static String getYoutubeVideoId(String youtubeUrl) {
String video_id = "";
if (youtubeUrl != null && youtubeUrl.trim().length() > 0 && youtubeUrl.startsWith("http")) {
String expression = "^.*((youtu.be" + "\\/)" + "|(v\\/)|(\\/u\\/w\\/)|(embed\\/)|(watch\\?))\\??v?=?([^#\\&\\?]*).*"; // var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
CharSequence input = youtubeUrl;
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(input);
if (matcher.matches()) {
String groupIndex1 = matcher.group(7);
if (groupIndex1 != null && groupIndex1.length() == 11)
video_id = groupIndex1;
}
}
return video_id;
}
}
yes , youtube main single global player if you start new player ,previous player will release automatically.
So you need restart your youtube player again when resume your activity
I'm trying to hook up Spotify with my Android app. I want to be able to hit a button and have the user be able to start playing from their library on the 4th tab of the TabLayout, and have the ability to swipe back and forth from one tab to another without the music stopping. Here is my current view:
Tabbed View
When I hit start broadcast, I just have it hooked up to SpotifyActivity.java where I've logged in and it starts playing a song. However, I want to have it so that I don't have to invoke a new activity when I want to start accessing my library and playing music so that I can switch between tabs and use the rest of the functionality of the app while the music plays. I recently learned about Services in Android and I was wondering if there was a way to use that. I basically want the flow to be like this:
The 4th tab presents a "start broadcast" button. Once this is hit, you log in to Spotify (or continue if you're already logged in), and a new view (activity?) pops up that gets Spotify and a UI working. Once the music starts, I can switch back to any of the first three tabs and interact with those while the music plays, and then when I go back to the first tab the activity pops up again with the music player UI and Spotify stuff. Here is my code for PageFragment:
public class PageFragment extends Fragment {
public static final String ARG_PAGE = "ARG_PAGE";
private static User thisUser;
private int mPage;
public static PageFragment newInstance(int page, User localUser) {
Bundle args = new Bundle();
thisUser = localUser;
args.putInt(ARG_PAGE, page);
PageFragment fragment = new PageFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPage = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = null;
TextView textView;
if (mPage == 1) {
//inflate the fragment_home_page
v = inflater.inflate(R.layout.fragment_home_page, container, false);
//handle profile and username information
}
else if (mPage == 2) {
//inflate the fragment_play_page
v = inflater.inflate(R.layout.fragment_play_page, container, false);
//handle music library information
}
else if(mPage == 3) {
//inflate the fragment_live_page
v = inflater.inflate(R.layout.fragment_live_page, container, false);
//handle live information
}
else if (mPage == 4) {
//inflate the fragment_nowplaying_page
v = inflater.inflate(R.layout.fragment_nowplaying_page, container, false);
Button startBroadcast = (Button) v.findViewById(R.id.start_broadcast);
//Links to SpotifyActivity
startBroadcast.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), SpotifyActivity.class);
startActivity(intent);
}
});
}
else {
Log.e("PageFragment ", "Unknown error occurred");
}
return v;
}
}
Here is my code for SpotifyActivity:
public class SpotifyActivity extends AppCompatActivity implements SpotifyPlayer.NotificationCallback, ConnectionStateCallback {
//CLIENT_ID=
//Callback
// Request code that will be used to verify if the result comes from correct activity
// Can be any integer
private static final int REQUEST_CODE = 1337;
private Player mPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spotify);
AuthenticationRequest.Builder builder = new AuthenticationRequest.Builder(CLIENT_ID,
AuthenticationResponse.Type.TOKEN,
REDIRECT_URI);
builder.setScopes(new String[]{"user-read-private", "streaming"});
AuthenticationRequest request = builder.build();
AuthenticationClient.openLoginActivity(this, REQUEST_CODE, request);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
//After the user logs in to authorize the application's scopes
// Check if result comes from the correct activity
if (requestCode == REQUEST_CODE) {
AuthenticationResponse response = AuthenticationClient.getResponse(resultCode, intent);
if (response.getType() == AuthenticationResponse.Type.TOKEN) {
Config playerConfig = new Config(this, response.getAccessToken(), CLIENT_ID);
Spotify.getPlayer(playerConfig, this, new SpotifyPlayer.InitializationObserver() {
#Override
public void onInitialized(SpotifyPlayer spotifyPlayer) {
mPlayer = spotifyPlayer;
mPlayer.addConnectionStateCallback(SpotifyActivity.this);
mPlayer.addNotificationCallback(SpotifyActivity.this);
}
#Override
public void onError(Throwable throwable) {
Log.e("MainActivity", "Could not initialize player: " + throwable.getMessage());
}
});
}
}
}
#Override
protected void onDestroy() {
Spotify.destroyPlayer(this);
super.onDestroy();
}
#Override
public void onPlaybackEvent(PlayerEvent playerEvent) {
Log.d("MainActivity", "Playback event received: " + playerEvent.name());
switch (playerEvent) {
// Handle event type as necessary
default:
break;
}
}
#Override
public void onPlaybackError(Error error) {
Log.d("MainActivity", "Playback error received: " + error.name());
switch (error) {
// Handle error type as necessary
default:
break;
}
}
#Override
public void onLoggedIn() {
Log.d("MainActivity", "User logged in");
mPlayer.playUri(null, "spotify:track:2TpxZ7JUBn3uw46aR7qd6V", 0, 0);
}
#Override
public void onLoggedOut() {
Log.d("MainActivity", "User logged out");
}
#Override
public void onLoginFailed(Error error) {
Log.d("MainActivity", "Login failed");
}
#Override
public void onTemporaryError() {
Log.d("MainActivity", "Temporary error occurred");
}
#Override
public void onConnectionMessage(String s) {
Log.d("MainActivity", "Received connection message: " + s);
}
}
Is there a way to set up Spotify's music player without losing it when I switch to other tabs?
How to get youtube key_vedio_id please help me to find-out this problem.
This is my code please and correct me if i wrong any where.
public class YouTubeActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
private static final int RECOVERY_DIALOG_REQUEST = 1;
public static final String KEY_VIDEO_ID = "KEY_VIDEO_ID";
private String mVideoId;
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_youtube);
final Bundle arguments = getIntent().getExtras();
if (arguments != null && arguments.containsKey(KEY_VIDEO_ID)) {
mVideoId = arguments.getString(KEY_VIDEO_ID);
}
final YouTubePlayerView playerView = (YouTubePlayerView) findViewById(R.id.youTubePlayerView);
playerView.initialize(getString(R.string.DEVELOPER_KEY_YOU_TUBE), this);
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean restored) {
//Here we can set some flags on the player
//This flag tells the player to switch to landscape when in fullscreen, it will also return to portrait
//when leaving fullscreen
youTubePlayer.setFullscreenControlFlags(YouTubePlayer.FULLSCREEN_FLAG_CONTROL_ORIENTATION);
//This flag tells the player to automatically enter fullscreen when in landscape. Since we don't have
//landscape layout for this activity, this is a good way to allow the user rotate the video player.
youTubePlayer.addFullscreenControlFlag(YouTubePlayer.FULLSCREEN_FLAG_ALWAYS_FULLSCREEN_IN_LANDSCAPE);
//This flag controls the system UI such as the status and navigation bar, hiding and showing them
//alongside the player UI
youTubePlayer.addFullscreenControlFlag(YouTubePlayer.FULLSCREEN_FLAG_CONTROL_SYSTEM_UI);
if (mVideoId != null) {
if (restored) {
youTubePlayer.play();
} else {
youTubePlayer.loadVideo(mVideoId);
}
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
if (youTubeInitializationResult.isUserRecoverableError()) {
youTubeInitializationResult.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
} else {
//Handle the failure
Toast.makeText(this, R.string.error_init_failure, Toast.LENGTH_LONG).show();
}
}
}
List youtube playlist from my playlist with ID PLSt1J_r1AmrzOUCGZ6sWNxvOePK4nOwIk into my android application but it is showing one video at a time but on want it to show the whole list of videos before I play any video.
My main activity code
public class MainActivity extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener{
public static final String API_KEY = "AIzaSyCe6tORd9Ch4lx-9Ku5SQ476uS9OtZYsWA";
public static final String VIDEO_ID = "o7VVHhK9zf0";
public static final String PlayList_ID = "PLP7qPet500dfglA7FFTxBmB_snxCaMHDJ";
private YouTubePlayer youTubePlayer;
private YouTubePlayerFragment youTubePlayerFragment;
private TextView textVideoLog;
private Button btnViewFullScreen;
private static final int RQS_ErrorDialog = 1;
String log = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
youTubePlayerFragment = (YouTubePlayerFragment)getFragmentManager()
.findFragmentById(R.id.youtubeplayerfragment);
youTubePlayerFragment.initialize(API_KEY, this);
textVideoLog = (TextView)findViewById(R.id.videolog);
btnViewFullScreen = (Button)findViewById(R.id.btnviewfullscreen);
btnViewFullScreen.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
youTubePlayer.setFullscreen(true);
}});
}
#Override
public void onInitializationFailure(Provider provider,
YouTubeInitializationResult result) {
if (result.isUserRecoverableError()) {
result.getErrorDialog(this, RQS_ErrorDialog).show();
} else {
Toast.makeText(this,
"YouTubePlayer.onInitializationFailure(): " + result.toString(),
Toast.LENGTH_LONG).show();
}
}
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player,
boolean wasRestored) {
youTubePlayer = player;
Toast.makeText(getApplicationContext(),
"YouTubePlayer.onInitializationSuccess()",
Toast.LENGTH_LONG).show();
if (!wasRestored) {
//player.cueVideo(VIDEO_ID);
player.cuePlaylist(PlayList_ID);
}
}
}
The playlist id, are the characters after "PL".
You can use recyclerView for the list. I have done this using Youtube api rest calls. You will need to get a browser key from the google developer console. I've explained this in my answer here:
https://stackoverflow.com/a/41201084/3689744
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.