如果我改变手机的方向,音乐会继续播放,这很好,但也不会暂停或停止。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_current_music);
musicState = String.valueOf(player.getState());
if (savedInstanceState != null)
{
musicState = savedInstanceState.getString("State");
}
player.state = MP3Player.MP3PlayerState.valueOf(musicState);
}
@Override
public void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putInt("Red", r);
outState.putInt("Green", g);
outState.putInt("Blue", b);
outState.putFloat("SPEED", playbackspeed);
outState.putInt("PROGRESS", progressUpdate);
outState.putInt("Update", updateIncrement);
outState.putInt("Duration", duration);
outState.putString("State", musicState);
}
public void onMusicBackClick ( View v ) {
Log. d (" g53mdp ", " button pressed !") ;
Intent intent = new Intent(CurrentMusic.this, MainActivity.class);
player.stop();
intent.putExtra("Red", r);
intent.putExtra("Green", g);
intent.putExtra("Blue", b);
intent.putExtra("SPEED", playbackspeed);
startActivity(intent);
finish();
}
public void onPlayClick (View v)
{
Log.d("MP3 Player", "Music Play button pressed");
if(player.getState() == MP3Player.MP3PlayerState.PAUSED)
{
player.play();
musicState = String.valueOf(player.getState());
}
else if(player.getState() == MP3Player.MP3PlayerState.PLAYING)
{
player.pause();
musicState = String.valueOf(player.getState());
}
else
{
player.load(musicURL, playbackspeed);
musicState = String.valueOf(player.getState());
updateIncrement = player.getDuration()/100;
duration = player.getDuration();
musicProgress = findViewById(R.id.p_musicProgress);
musicProgress.setMax(duration);
progress = player.getProgress();
timer.scheduleAtFixedRate(timerTask = new TimerTask(){
@Override
public void run() {
progress = player.getProgress();
progressUpdate = progress;
musicProgress.setProgress(progress);
}
}, 0, updateIncrement);
}
}
public void onPauseClick (View v)
{
Log.d("MP3 Player", "Music pause button pressed");
if(player.getState() == MP3Player.MP3PlayerState.PLAYING)
{
player.pause();
}
}
public void onStopClick (View v)
{
Log.d("MP3 Player", "Music stop button pressed");
if(player.getState() == MP3Player.MP3PlayerState.PAUSED || player.getState() == MP3Player.MP3PlayerState.PLAYING)
{
player.stop();
}
player.stop();
}
我认为只需将值转换为字符串,然后提取它并将其放回去就可以了,但是如果你播放媒体文件并调整手机方向,它几乎就会变得异常。
我正在打印状态并检查每次交互下的每个状态,甚至在定向后重新创建活动后,它会说并告诉我它实际上已停止,但它仍然在玩?
您的问题是,重新创建活动时,对 MP3 播放器实例的引用不会持续存在,但由于它正在播放音乐,因此仍然存在于后台。在 Activity 生命周期中持久保存任何内容的正确方法是使用 ViewModel,您应该创建一个并在其中存储您的 MP3 播放器实例。
我找到了一个解决方案,这个解决方案是否好我不知道,我已经将其发布在我的另一篇文章中