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();
}
}
}
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 have a container where I show a GIF video.On click of the GIF it opens the same video in YouTube. YouTubePlayerView has maximize and minimize icon, when I click on that video is just restarting instead of minimizing it and get back to the same container. I am not sure how to minimize the video which is playing in YouTubePlayerView.
I have created a separate Activity called YouTubeACtivity:
public class YoutubeActivity extends AppCompatActivity {
String shortCode = "";
public static void show(Activity activity, String shortCode)
{
Intent intent = new Intent(activity, YoutubeActivity.class);
intent.putExtra(Constants.YOUTUBE_VIDEO, shortCode);
activity.startActivity(intent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_youtubeplayer);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
shortCode = getIntent().getStringExtra(Constants.YOUTUBE_VIDEO);
YouTubePlayerFragment mYoutubePlayerFragment = new YouTubePlayerFragment().newInstance();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.youtubeContainer, mYoutubePlayerFragment);
ft.commit();
if (mYoutubePlayerFragment != null) {
mYoutubePlayerFragment.initialize(getResources().getString(R.string.google_api_key), new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean restored) {
//youTubePlayer.setFullscreen(true);
youTubePlayer.addFullscreenControlFlag(YouTubePlayer.FULLSCREEN_FLAG_ALWAYS_FULLSCREEN_IN_LANDSCAPE| YouTubePlayer.FULLSCREEN_FLAG_CONTROL_ORIENTATION);
// youTubePlayer. setShowFullscreenButton(false);
youTubePlayer.setOnFullscreenListener(new YouTubePlayer.OnFullscreenListener() {
#Override
public void onFullscreen(boolean fullscreen) {
// onBackPressed();
}
});
Log.e("shortcode ", "reached" + shortCode);
if (shortCode != null) {
if (restored) {
youTubePlayer.play();
} else {
youTubePlayer.loadVideo("" + shortCode + "");
}
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
Log.e("youtube initialization ", "initialisation fails");
}
});
}
}
}
The GIF video is showing in a FrameLayout which implements SurfaceHolder callback.
I just wanted to know is there anyway we can make minimize the video and comeback to the container layout.
First I suggest to use the player object to go or exit fullscreen
youtubeplayer.setFullScreen(true/false);
then add config changes in manifest of the activity containing the container
android:configChanges="orientation|screenSize|keyboardHidden|screenLayout"
as far as i can understand your problem your activity is getting restarted
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 am successfully integrate YouTube Android Player API for my apps. I am curious to know about which file is rendered in the player. Every single video file may have several formats like 320dpi,720dpi & etc.
If my users, is in lower bandwidth; can i choose the file format or the API automatically detects which version would be played in that situation and vice-verse. My code:
public class YoutubeVideoActivity extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener, YouTubePlayer.OnFullscreenListener {
Activity activity = YoutubeVideoActivity.this;
public static final String API_KEY = "AIzaSyDN6Q9Pv4seQZqIcjB*********Po5k";
// public static final String VIDEO_ID = "psY0Botpi84";
public String new_id;
private boolean fullscreen;
private YouTubePlayerView playerView;
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
// Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_youtube_video);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
Intent intent = getIntent();
String video_link = intent.getExtras().getString("video_link");
try {
new_id = video_link.substring("http://www.youtube.com/watch?v="
.length());
if (new_id.equals("")) {
IndepententTVUtils.showCustomAlert(activity,
"Data is not availble. Press back key",
R.drawable.ic_new_launcher);
} else {
playerView = (YouTubePlayerView) findViewById(R.id.youtubeplayerview);
playerView.initialize(API_KEY, this);
}
} catch (Exception e) {
IndepententTVUtils.showCustomAlert(activity,
"Data is not availble", R.drawable.ic_new_launcher);
}
}
#Override
public void onInitializationFailure(Provider arg0,
YouTubeInitializationResult arg1) {
Toast.makeText(getApplicationContext(),
"To See this Video, Install Latest YouTube Application",
Toast.LENGTH_LONG).show();
}
#Override
public void onInitializationSuccess(Provider arg0, YouTubePlayer player,
boolean wasRestored) {
player.setOnFullscreenListener(this);
if (!wasRestored && new_id != null) {
player.cueVideo(new_id);
}
}
#Override
public void onFullscreen(boolean isFullscreen) {
fullscreen = isFullscreen;
}
}
The player sets video quality automatically according to the users bandwidth or internet speed, if it was not so there would be an option specifying the setPlaybackQuality in player.
There are only restricted options to change the player settings that are
here