停止播放器后,需要重新准备播放器。如果您想在应用程序进入后台时停止播放,并在应用程序进入前台时从头开始播放媒体。只需将您的BroadcastReceiver代码修改为此:
private BroadcastReceiver StateReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String status = intent.getStringExtra("status"); if (parseInt(String.valueOf(status)) == 0) { player.stop(); } else { player = MediaPlayer.create(this, R.raw.music); player.setLooping(true); player.start(); } } };但是,如果要暂停播放并从离开的位置继续播放,请进行以下更改:在Application类的onActivityDestroyed()中:
@Overridepublic void onActivityDestroyed(Activity activity) { send_status(2);}并在BroadcastReceiver中:
private BroadcastReceiver StateReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String status = intent.getStringExtra("status"); if (parseInt(String.valueOf(status)) == 0) { player.pause(); //When app is in background and not killed, we just want to pause the player and not want to lose the current state. } else if (parseInt(String.valueOf(status)) == 1) { if (player != null) player.start(); // If the player was created and wasn't stopped, it won't be null, and the playback will be resumed from where we left of. else { // If the player was stopped, we need to prepare it once again. player = MediaPlayer.create(this, R.raw.music); player.setLooping(true); player.start(); } } else if(player != null){ player.stop(); player.release(); } } };另外,看看MediaPlayer的状态。



