私のアプリケーションでは、バックグラウンドミュージックは非同期タスクによって制御されます。ホームボタンを押すと音楽が止まります。電源ボタンを押すと、再生を続けます。また、電源ボタンを押してから再開すると、同時に曲のコピーが開始されることにも気づきました。
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();
}
}