我想在我的Android应用中播放YouTube视频。我创建了新的API并下载了Jar文件,然后将其添加到libs文件夹中。终于做了同步。
compile files('libs/YouTubeAndroidPlayerApi.jar')
然后我添加了布局
<com.google.android.youtube.player.YouTubePlayerView
android:id="@+id/youtube_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
在java文件中
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_promo);
youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
youTubeView.initialize(Config.YOUTUBE_API_KEY, promo.this);
}
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
if (!b) {
youTubePlayer.cueVideo("fhWaJi1Hsfo"); // Plays https://www.youtube.com/watch?v=fhWaJi1Hsfo
}
}
@Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
if (youTubeInitializationResult.isUserRecoverableError()) {
youTubeInitializationResult.getErrorDialog(promo.this, RECOVERY_REQUEST).show();
} else {
String error = String.format(getString(R.string.player_error), youTubeInitializationResult.toString());
Toast.makeText(promo.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, promo.this);
}
}
protected YouTubePlayer.Provider getYouTubePlayerProvider() {
return youTubeView;
}
还在清单
中添加了互联网权限<uses-permission android:name="android.permission.INTERNET" />