我在Android应用中使用YouTube API
。这是代码。
MainActivity.java
package com.example.graphs.youtubeapitext;
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.YouTubePlayer.Provider;
import com.google.android.youtube.player.YouTubePlayerFragment;
import com.google.android.youtube.player.YouTubePlayerView;
public class MainActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
private static final int RECOVERY_REQUEST = 1;
private YouTubePlayerView youTubeView;
private YouTubePlayerFragment youTubePlayerFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
youTubeView.initialize(Config.YOUTUBE_API_KEY, this);
// youTubePlayerFragment = (YouTubePlayerFragment) getFragmentManager()
// .findFragmentById(R.id.youtube_fragment);
// youTubePlayerFragment.initialize(Config.YOUTUBE_API_KEY, this);
}
@Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
player.cueVideo("fhWaJi1Hsfo"); // Plays https://www.youtube.com/watch?v=fhWaJi1Hsfo
}
}
@Override
public void onInitializationFailure(Provider provider, YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(this, RECOVERY_REQUEST).show();
} else {
String error = String.format(getString(R.string.player_error), errorReason.toString());
Toast.makeText(this, 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(Config.YOUTUBE_API_KEY, this);
}
}
protected Provider getYouTubePlayerProvider() {
return youTubeView;
}
}
activity_main.xml中
<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"/>
<!--<fragment-->
<!--android:id="@+id/youtube_fragment"-->
<!--android:name="com.google.android.youtube.player.YouTubePlayerFragment"-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="wrap_content" />-->
</RelativeLayout>
如何启用modestbranding
为1? modestbranding是您可以在Youtube网址中使用的参数,用于自定义播放器。