【问题标题】:CountDownTimer onFinish() not called if I call cancel() when activity is pausing如果我在活动暂停时调用 cancel(),则不会调用 CountDownTimer onFinish()
【发布时间】:2012-10-20 20:47:49
【问题描述】:

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

我在onPause 的CountDownTimer 上调用cancel(),但似乎由于活动正在暂停,CountDownTimer 在销毁之前从未收到消息(?),因此 CountDownTimer 的finish()没有被调用。

这样做的结果是,在退出应用程序后,音乐会继续以 CountDownTimer 中上次设置的音量继续播放,但永远不会结束。所以现在我被困在我的应用程序之外,MediaPlayer 正在运行并且无法停止它(非常糟糕)。

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

这是我的代码:

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

在 onPause 中:

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

如果一切正常,我会看到“正在取消淡入淡出计时器”日志消息,然后是“淡入淡出计时器完成,正在释放”,但我从未收到 onFinish() logcat 消息。

我只看到这个:

 tag     Song stopping, starting fade timer.
 tag     Application exiting, destroying all audio resources
 tag     Cancelling fade timer on destroy.

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

【问题讨论】:

    标签: android android-activity countdowntimer


    【解决方案1】:

    看看source code。你会看到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();
    

    【讨论】:

    • 啊,感谢您提醒我这一点。我在其他地方读到取消确实明确调用onFinish,但我想那是错误的。应该先检查一下。谢谢!
    • 没问题。我个人对这个课程有一些不满,我和另一个用户在his question 中讨论过。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-05
    • 1970-01-01
    相关资源
    最近更新 更多