如果我在活动暂停时调用cancel(),则不会调用CountDownTimer onFinish()

Tim*_*Tim 0 android android-activity countdowntimer

我有一个活动,通过一个音乐播放一些音乐MediaPlayer.通常,当我想要停止播放歌曲时,我将MediaPlayer传递给CountDownTimer将音量淡化为零的音量,然后释放MediaPlayer.这似乎工作正常,但我的活动暂停时遇到问题,例如在触摸主页按钮后.

我正在调用cancel()CountDownTimer onPause,但似乎由于活动暂停,CountDownTimer在销毁之前从不接收消息(?),因此finish()不会调用CountDownTimer.

这样做的结果是,在退出应用程序后,音乐将继续以CountDownTimer中最后设置的任何音量播放,但它永远不会完成.所以现在我已经停止运行MediaPlayer的应用程序,无法阻止它(非常糟糕).

onFinish即使我调用取消,当活动退出时,CountDownTimer不会被调用是否正常?

这是我的代码:

public void StopSong(boolean fadeout){
    musicPlaying = false;
    if(_player != null) {
        final int fadeTime = 1000;
        CountDownTimer timer = new CountDownTimer(fadeTime,50) {
            final private MyMusicPlayer mFadePlayer = _player;

            @Override
            public void onTick(long millisUntilFinished) {
                mFadePlayer.setFade((float)millisUntilFinished / (float)fadeTime);
                Log.d("tag", "Fade timer " + millisUntilFinished+ "ms remaining.");
            }

            @Override
            public void onFinish() {
                mFadePlayer.stop();
                mFadePlayer.release();
                Log.d("tag", "Fade timer finished, releasing resource.");
            }
        };
        timer.start();
        mFadeTimers.add(timer);
        Log.d("tag", "Song stopping, starting fade timer.");
        _player = null;
    }
}
Run Code Online (Sandbox Code Playgroud)

并在onPause:

    for(CountDownTimer t : mFadeTimers){
        Log.d("tag", "Cancelling fade timer on destroy.");
        t.cancel();
    }
    mFadeTimers.clear();
Run Code Online (Sandbox Code Playgroud)

如果一切正常,我会看到"取消淡入淡出定时器"日志消息,然后是"淡化定时器已完成,释放",但我从未收到过onFinish()logcat消息.

我只是看到了这个:

 tag     Song stopping, starting fade timer.
 tag     Application exiting, destroying all audio resources
 tag     Cancelling fade timer on destroy.
Run Code Online (Sandbox Code Playgroud)

如何在退出活动时成功中止所有倒计时器?

Sam*_*Sam 14

看一下源代码.你会看到cancel()没有调用onFinish(),这就是CountDownTimer的设计方式.

你可以打电话给onFinish()自己:

for(CountDownTimer t : mFadeTimers){
    Log.d("tag", "Cancelling fade timer on destroy."); // ought to read "in onPause", right?
    t.cancel();
    t.onFinish();
}
mFadeTimers.clear();
Run Code Online (Sandbox Code Playgroud)