YouTubeAndroidPlayerAPI异常:返回FirstActivity后视频持续加载无法播放
Hey there, I’ve run into this exact issue before—that Forcefully created overlay warning is a dead giveaway that your YouTube Player lifecycle management is off. Let’s break down how to fix the problem where your video gets stuck loading after returning to FirstActivity from SecondActivity.
Root Cause
When you navigate away from FirstActivity to SecondActivity, if you don’t properly release the YouTubePlayer instance or save its state, the player’s underlying view can get into a messed-up state. When you come back, the system tries to force an overlay to render the player, but it can’t properly attach to the Activity’s window, leading to the endless loading loop.
Step-by-Step Fix
1. Track Playback State & Video ID
First, add member variables to your FirstActivity to keep track of the video you’re playing, your current position, and whether the video was playing before you left:
private YouTubePlayerView youtubePlayerView; private YouTubePlayer youtubePlayer; private String currentVideoId = "YOUR_VIDEO_ID"; // Replace with your target video ID private int playbackPosition = 0; private boolean wasPlaying = false;
2. Properly Initialize the Player
Make sure your initialization logic handles state restoration (this is key for when you return to the Activity):
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_first); youtubePlayerView = findViewById(R.id.youtube_player_view); youtubePlayerView.initialize("YOUR_API_KEY", new YouTubePlayer.OnInitializedListener() { @Override public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) { youtubePlayer = player; // Track playback state to save later player.setPlayerStateChangeListener(new YouTubePlayer.PlayerStateChangeListener() { @Override public void onLoading() {} @Override public void onLoaded(String videoId) { // Restore previous position if we have one saved if (playbackPosition > 0) { player.seekToMillis(playbackPosition); if (wasPlaying) { player.play(); } } else if (!wasRestored) { player.loadVideo(currentVideoId); } } @Override public void onAdStarted() {} @Override public void onVideoStarted() { wasPlaying = true; } @Override public void onVideoEnded() { wasPlaying = false; } @Override public void onError(YouTubePlayer.ErrorReason errorReason) {} }); // Handle automatic state restoration (e.g., after configuration change) if (wasRestored) { player.play(); } else { player.loadVideo(currentVideoId); } } @Override public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult errorReason) { // Add your error handling here (e.g., show a toast or error dialog) } }); }
3. Manage the Player Lifecycle
This is the most critical part. You need to save state when the Activity pauses, release the player when it stops, and reinitialize when it resumes:
@Override protected void onPause() { super.onPause(); // Save current playback state before leaving the Activity if (youtubePlayer != null) { playbackPosition = youtubePlayer.getCurrentTimeMillis(); wasPlaying = youtubePlayer.isPlaying(); youtubePlayer.pause(); } } @Override protected void onStop() { super.onStop(); // Release the player to free up resources and avoid overlay conflicts if (youtubePlayer != null) { youtubePlayer.release(); youtubePlayer = null; } } @Override protected void onResume() { super.onResume(); // Reinitialize the player if it was released when the Activity stopped if (youtubePlayerView != null && youtubePlayer == null) { youtubePlayerView.initialize("YOUR_API_KEY", this); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); // Persist state across Activity restarts or configuration changes outState.putString("currentVideoId", currentVideoId); outState.putInt("playbackPosition", playbackPosition); outState.putBoolean("wasPlaying", wasPlaying); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); // Retrieve saved state when the Activity is restored currentVideoId = savedInstanceState.getString("currentVideoId"); playbackPosition = savedInstanceState.getInt("playbackPosition"); wasPlaying = savedInstanceState.getBoolean("wasPlaying"); }
4. Double-Check Your Layout
Ensure your YouTubePlayerView has valid layout parameters (avoid wrap_content for width/height if possible—use match_parent or fixed dimensions). A misconfigured view can trigger the overlay warning too.
Why This Works
- By releasing the player in
onStop(), you’re telling the YouTube API to clean up all its resources, preventing the broken overlay from being created when you return. - Saving and restoring the playback state ensures your video picks up right where it left off, rather than starting from scratch.
- Reinitializing the player in
onResume()guarantees that the player is properly attached to the Activity’s window when you return.
内容的提问来源于stack exchange,提问作者NagarjunaReddy

