I want to play youtube videos using new Android Youtube API. I have download demo project from google (YouTubeAndroidAPIDemo) and this is the code I use to launch a video:
Intent intent = YouTubeStandalonePlayer.createVideoIntent(this, getString(R.string.ID_DEVELOPER_KEY), "cdgQpa1pUUE", 0, true, false);
startActivityForResult(intent, 1);
This running the youtube video ok, but, when the user press back key, I want to know time elapsed (for example, the youtube video size is 3:01, but the user only have seen 50 seconds)
How can I know time elapsed?
Thanks!
Finally I got my target creating another activity, put in a bundle the ID of the youtube video that I want to launch, and adding an atributte of the YouTubePlayer class, loading it in the onInitializationSuccess function. Here is my code:
public class Youtube_Activity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
private String mVideo;
private int mInicio;
private YouTubePlayerView mYouTubeView;
private YouTubePlayer mPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.youtube_activity);
Bundle extra = getIntent().getExtras();
mVideo = extra.getString("video");
mYouTubeView = (YouTubePlayerView)findViewById(R.id.youtube_view);
mYouTubeView.initialize(getString(R.string.ID_DEVELOPER_KEY), this);
}
#Override
public void onInitializationFailure(Provider provider,YouTubeInitializationResult error) {
Toast.makeText(this, "Oh no! "+error.toString(),Toast.LENGTH_LONG).show();
}
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player,boolean wasRestored) {
player.loadVideo(mVideo);
mPlayer = player;
}
#Override
public void finish() {
Intent data = new Intent();
int t = (mPlayer.getCurrentTimeMillis()/1000);
data.putExtra("tiempo",t );
setResult(0, data);
super.finish();
}
Related
Hi i follow tutorial on CodingwithMitch about using Youtube API in android. It is a good tutorial to start.
Everything is running perfectly however when the player is idle the screen is just blank instead of showing the video thumbnail/preview.
screenshot of my app
I would like to make the idle screen shows vid thumbnail so i know what video will be played.
The code in MyActivity.xml is below:
<view class="com.google.android.youtube.player.YouTubePlayerView"
android:id="#+id/youtubePlay"
android:layout_width="match_parent"
android:layout_height="200dp"
android:orientation="vertical"
YouTube Config code:
public class YouTubeConfig {public YouTubeConfig() {} private static final String API_KEY = "AIzaSyXXXXXX";public static String getApiKey(){
return API_KEY;}}
And in my MainActivity.java
private static final String TAG = "MainActivity";
YouTubePlayerView mYoutubePlayerView;
Button btnPlay;
YouTubePlayer.OnInitializedListener mOnInitializedListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//PlayYouTube
Log.d(TAG, "onCreate: Starting.");
btnPlay = (Button) findViewById(R.id.btnPlay);
mYoutubePlayerView = (YouTubePlayerView) findViewById(R.id.youtubePlay);
mOnInitializedListener = new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
Log.d(TAG, "onInitializationSuccess: Done Initialising.");
youTubePlayer.loadPlaylist("PLZRTg9sNaMaFnh04-HODVcYRlFtKO8rsS");
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
Log.d(TAG, "onInitializationSuccess: Fail to Initialize.");
}
};
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: Initializing Youtube Player.");
mYoutubePlayerView.initialize(YouTubeConfig.getApiKey(), mOnInitializedListener);
}
});
Any help would be really appreciated
You need to supply the thumbnail for the youtube video that you want its preview to display.
Get a thumbnail from youtube video
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
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
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 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