我面临的问题是,当使用最近的应用程序恢复包含媒体播放器的活动时,媒体播放器在单击图像时无法正确播放。当使用后退按钮关闭应用程序,然后使用最近的应用程序重新打开时,媒体播放器可以正常工作。但是,如果使用主页按钮关闭应用程序,然后使用最近的应用程序重新打开,媒体播放器即使在点击图像时也不播放。
public class MainActivity extends AppCompatActivity {
private static final String STATE_MEDIA_PLAYER = "media_player_state";
private static final String STATE_AUDIO_PLAYING = "audio_playing_state";
ImageView imageView;
GifImageView gifImageView;
MediaPlayer mediaPlayer;
boolean isAudioPlaying = false;
private AdView mAdView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
@Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
imageView = findViewById(R.id.imageRickroll);
gifImageView = findViewById(R.id.gifImage);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!isAudioPlaying) {
mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.rickroll_song);
if (mediaPlayer != null) {
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
gifImageView.setVisibility(View.GONE);
mediaPlayer.stop();
mediaPlayer.release();
isAudioPlaying = false;
}
});
mediaPlayer.start();
isAudioPlaying = true;
}
}
gifImageView.setImageResource(R.drawable.deadserver);
gifImageView.setVisibility(View.VISIBLE);
}
});
}
private void stopAndReleaseMediaPlayer() {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
}
@Override
protected void onStop() {
super.onStop();
gifImageView.setVisibility(View.GONE);
stopAndReleaseMediaPlayer();
}
@Override
protected void onPause() {
super.onPause();
if (mediaPlayer != null) {
mediaPlayer.pause();
}
}
@Override
protected void onResume() {
super.onResume();
if (mediaPlayer != null && isAudioPlaying) {
mediaPlayer.start();
}
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putBoolean(STATE_AUDIO_PLAYING, isAudioPlaying);
if (mediaPlayer != null) {
int currentPosition = mediaPlayer.getCurrentPosition();
savedInstanceState.putInt(STATE_MEDIA_PLAYER, currentPosition);
}
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
isAudioPlaying = savedInstanceState.getBoolean(STATE_AUDIO_PLAYING);
int currentPosition = savedInstanceState.getInt(STATE_MEDIA_PLAYER, 0);
if (mediaPlayer != null && isAudioPlaying) {
mediaPlayer.seekTo(currentPosition);
mediaPlayer.start();
}
}
}
1条答案
按热度按时间ozxc1zmp1#
如果您使用
则不能再重复使用。