在我的应用程序中,背景音乐由异步任务控制。按下主页按钮时,音乐关闭。按下电源按钮时,它会继续播放。我还意识到,如果我按下电源按钮然后恢复它,它会同时开始复制歌曲。
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();
}
}