Android端MediaPlayer播放完成后按返回键弹出“无法播放此视频”错误
Hey there! I’ve run into this exact annoying issue before—nothing’s more frustrating than that random native Android dialog popping up after a video finishes playing, right? Let’s break down why this happens and how to fix it.
Why This Happens
When your video finishes playing, the underlying MediaPlayer (or VideoView, which wraps it) might slip into an idle or error state, but the error listener is still attached. When you navigate back and the current form gets destroyed, the system tries to clean up the media player, which triggers the error callback and throws up that unwanted dialog. When you return mid-playback, the player’s still in a valid active state, so no error gets triggered.
Solutions to Try
1. Clean Up MediaPlayer Immediately When Video Ends
First, make sure you explicitly stop and release the media player as soon as the video finishes. If you’re using VideoView, set an OnCompletionListener to handle this cleanup:
videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { // Stop and release the player to clear leftover invalid states mp.stop(); mp.release(); // Reset the VideoView to a clean state too videoView.stopPlayback(); } });
2. Double Down on Cleanup in Lifecycle Methods
Even if you handle completion, it’s smart to add a safety net in your form’s lifecycle methods. Override onDestroy() (or onStop() if you want to handle partial lifecycle events) to ensure the media player is properly released:
@Override protected void onDestroy() { super.onDestroy(); if (videoView != null) { videoView.stopPlayback(); // If you hold a direct reference to MediaPlayer: // if (mediaPlayer != null) { // mediaPlayer.stop(); // mediaPlayer.release(); // mediaPlayer = null; // } } }
3. Suppress the Native Error Dialog (For VideoView Users)
If the above steps don’t do the trick, you can override VideoView to block the default error dialog entirely. Create a custom VideoView class:
public class CustomVideoView extends VideoView { public CustomVideoView(Context context) { super(context); } public CustomVideoView(Context context, AttributeSet attrs) { super(context, attrs); } public CustomVideoView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onError(int what, int extra) { // Skip calling super.onError() to prevent the native dialog from appearing // You can add silent error handling here if needed } }
Then replace the standard VideoView in your layout with this custom version.
Quick Final Check
Make sure you’re not reusing the same MediaPlayer instance without resetting it properly between video plays. Every time you start a new video, confirm the player’s in a clean, reset state.
Give these steps a shot—they should get rid of that unwanted error dialog when returning after video completion!
内容的提问来源于stack exchange,提问作者ygesher

