i m using following code to access youtube but on run time it is giving "class not found exception" i already added all Jar's reqiured
String developer_key="my Key";
#Override
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
YouTubeService service = new YouTubeService( developer_key);
}
It's no longer that simple.
You must first create your UX element (YouTubePlayerView, YouTubePlayerFragment, YouTubeStandalonePlayer, etc), then you send the initialize message to it.
From the YouTube Android API Demo App PlayerViewDemoActivity.java:
/**
* A simple YouTube Android API demo application which shows how to create a simple application that
* displays a YouTube Video in a {#link YouTubePlayerView}.
* <p>
* Note, to use a {#link YouTubePlayerView}, your activity must extend {#link YouTubeBaseActivity}.
*/
public class PlayerViewDemoActivity extends YouTubeFailureRecoveryActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playerview_demo);
YouTubePlayerView youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
youTubeView.initialize(DeveloperKey.DEVELOPER_KEY, this);
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player,
boolean wasRestored) {
if (!wasRestored) {
player.loadVideo("wKJ9KzGQq0w");
}
}
#Override
protected YouTubePlayer.Provider getYouTubePlayerProvider() {
return (YouTubePlayerView) findViewById(R.id.youtube_view);
}
}
From YouTubeFailureRecoveryActivity.java:
/**
* An abstract activity which deals with recovering from errors which may occur during API
* initialization, but can be corrected through user action.
*/
public abstract class YouTubeFailureRecoveryActivity extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener {
private static final int RECOVERY_DIALOG_REQUEST = 1;
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
} else {
String errorMessage = String.format(getString(R.string.error_player), errorReason.toString());
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
}
#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(DeveloperKey.DEVELOPER_KEY, this);
}
}
protected abstract YouTubePlayer.Provider getYouTubePlayerProvider();
}
Related
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);
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();
}
}
}
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.
Am new in android development.Am trying to implement youtube Api. But in my XML file it show error "could not be instantiated:
- com.google.android.youtube.player.YouTubePlayerView"
Here is My MAinActivity Code:-
public class MainActivity extends YouTubeBaseActivity {
Button b;
private YouTubePlayerView youtubeplayerview;
private YouTubePlayer.OnInitializedListener onInitializedListener;
#Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
setContentView(R.layout.activity_main);
youtubeplayerview=(YouTubePlayerView)findViewById(R.id.Youtube_view);
onInitializedListener=new YouTubePlayer.OnInitializedListener(){
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
youTubePlayer.loadVideo("wvjqFy33HVA");
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
};
b=(Button)findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
youtubeplayerview.initialize("API KEY",onInitializedListener);
}
});
}
}
Here is my XML file Code:-
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="PLAY VEDIO"
android:id="#+id/button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<com.google.android.youtube.player.YouTubePlayerView
android:layout_width="500dp"
android:layout_height="500dp"
android:id="#+id/Youtube_view"
android:layout_alignParentTop="true"
android:layout_above="#+id/button"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
Here is Error Screenshot
Did you add YouTube Android Player API to your library? Adding that fixed the issue for me..Try adding the same by following the steps given below :
1.Download YouTube Android Player API jar file from https://developers.google.com/youtube/android/player/downloads/
2.Extract the zip file, go to libs -> YouTubeAndroidPlayerApi.jar and copy it
3.Paste the jar file to /app/libs/ directory in android studio
Finally add compile files('libs/YouTubeAndroidPlayerApi.jar') to your app level build.gradle file
Sync,build and check if it works fine
Did you generate api key for android youtube player?
Link: https://console.developers.google.com
If yes, you must to change "API KEY " in this youtubeplayerview.initialize("API KEY",onInitializedListener); by your api key that you generated before.
Anyway, you can try to replace you class by this class with YoutubeDeveloperKey is the key you generated :
public class ActivityPlayYouTube extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener {
private YouTubePlayer YPlayer;
private static final String YoutubeDeveloperKey = "YOUR_DEVELOPER_KEY_GOES_HERE";
private static final int RECOVERY_DIALOG_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playyoutube);
YouTubePlayerView youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
youTubeView.initialize(YoutubeDeveloperKey, this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.you_tube_api, menu);
return true;
}
#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",
errorReason.toString());
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
}
#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(YoutubeDeveloperKey, this);
}
}
protected YouTubePlayer.Provider getYouTubePlayerProvider() {
return (YouTubePlayerView) findViewById(R.id.youtube_view);
}
#Override
public void onInitializationSuccess(Provider provider,
YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
YPlayer = player;
/*
* Now that this variable YPlayer is global you can access it
* throughout the activity, and perform all the player actions like
* play, pause and seeking to a position by code.
*/
YPlayer.cueVideo("2zNSgSzhBfM");
}
}
}
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