我用MainActivity播放视频,视频播放得很好。在播放视频时,如果我再次打开相同的活动并返回到以前的MainActivity,youtube进度条一直在转动,什么也没有发生。我阅读了文档,但找不到任何与此问题相关的内容。实际上,文档非常旧(2015年更新),YouTubeAndroidPlayerApi库在2017年更新。请给我指引正确的方向。
MainActivity.java
public class MainActivity extends YouTubeBaseActivity
implements YouTubePlayer.OnInitializedListener {
private String YOUTUBE_API_KEY = "api_key";
private YouTubePlayerView youtubePlayerView;
@Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_main);
youtubePlayerView = findViewById(R.id.youtubePlayer);
youtubePlayerView.initialize(YOUTUBE_API_KEY, this);
}
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
Log.w("youtube_activity", "onInitialization success");
youTubePlayer.loadVideo("0KSOMA3QBU0");
}
@Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
Toast.makeText(this, "Initialization failure", Toast.LENGTH_SHORT);
}
public void onClick(View view) {
startActivity(new Intent(this, MainActivity.class));
}
}布局xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.youtube.player.YouTubePlayerView
android:id="@+id/youtubePlayer"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</com.google.android.youtube.player.YouTubePlayerView>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:onClick="onClick"
android:text="Button" />
</LinearLayout>

发布于 2018-02-09 15:14:03
找到了在转到另一个youtubeplayeractivity活动时释放YouTubePlayer的解决方案。当返回到之前的youtubeplayeractivity时,重新初始化了YouTubePlayerView。
public void onClick(View view) {
youTubePlayer.release();
startActivity(new Intent(this, MainActivity.class));
}
@Override
protected void onRestart() {
super.onRestart();
youtubePlayerView.initialize(YOUTUBE_API_KEY, this);
}https://stackoverflow.com/questions/48698599
复制相似问题