不再那么简单了。
您必须首先创建您的 UX 元素(YouTubePlayerView、YouTubePlayerFragment、YouTubeStandalonePlayer 等),然后向其发送初始化消息。
来自 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);
}
}
来自 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();
}