2

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

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();
    }

}
4

3 回答 3

2

AFAIK 按下电源按钮时,只onpause调用而不onstop调用,由于没有其他活动进入前台,只有一个系统窗口出现在顶部。因此,您的结束通话没有被调用。

更好的方法是在 OnPause 而不是 onstop 中覆盖Asynctask.onCancelled 和调用方法Asynctask.cancel

于 2012-09-03T03:24:46.880 回答
1

只需添加,您需要覆盖 onCancelled() 并在 doInBackground() 中添加检查。请参阅:取消正在执行的 AsyncTask 的理想方法

于 2012-09-03T03:21:53.947 回答
0

你必须取消你的 asyncTask。您应该在 Activity 的 onDestroy() 中调用 asyncTask.cancel(true)。

于 2012-09-03T02:59:03.167 回答