在我的应用程序中,背景音乐由asynctask控制。按下主页按钮时,音乐将关闭。按下电源按钮后,它会继续播放。我也意识到,如果我按下电源按钮然后恢复它,它会同时开始复制这首歌。
private single s;
private BackgroundSound mBackgroundSound = new BackgroundSound();
protected void onPause(){
super.onPause();
Log.d("mSTATE","PAUSE");
s.onPause();
mBackgroundSound.cancel(true);
}
public void onBackPressed() {
super.onBackPressed();
return;
}
protected void onDestroy(){
super.onDestroy();
Log.d("mState","DESTROY");
}
public void onWindowFocusChanged(boolean change){
super.onWindowFocusChanged(change);
}
@Override
protected void onResume(){
super.onResume();
mBackgroundSound = new BackgroundSound();
mBackgroundSound.execute(null);
Log.d("mSTATE","RESUME");
s.onResume();
}
@Override
protected void onStop(){
super.onStop();
Log.d("mSTATE","STOP");
s.freeMemory();
mBackgroundSound.end();
}
@Override
protected void onRestart(){
super.onRestart();
Log.d("mSTATE","RESTART");
}
@Override
protected void onStart(){
super.onStart();
Log.d("mSTATE","STARTER");
}
public class BackgroundSound extends AsyncTask<Void, Void, Void> {
private MediaPlayer player;
protected void onPreExecute() {
player = MediaPlayer.create(SingleActivity.this, R.raw.song);
}
@Override
protected Void doInBackground(Void... params) {
player.setLooping(true);
AudioManager mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_RING);
int maxRingerVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_RING);
double proportion = currentVolume/(double)maxRingerVolume;
int maxMusicVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
int volume = (int)(proportion * maxMusicVolume);
player.setVolume(volume,volume);
player.setLooping(true);
player.start();
return null;
}
public void end(){
player.stop();
player.release();
}
}
答案 0 :(得分:2)
AFAIK按下电源按钮时,仅调用onpause
且未调用onstop
,因为没有其他活动到达前台,只有一个系统窗口位于顶部。因此,您的结束通话未被调用。
更好的方法是覆盖Asynctask.onCancelled
并在OnPause中调用Asynctask.cancel
方法而不是onstop
答案 1 :(得分:1)
只需添加,您需要覆盖onCancelled()并添加check in doBackground()。 请参阅:Ideal way to cancel an executing AsyncTask
答案 2 :(得分:0)
您必须取消asyncTask。 您应该在Activity的onDestroy()中调用asyncTask.cancel(true)。