离开并返回活动后,使用计时器onTick更新TextView

时间:2016-12-30 14:21:46

标签: java android android-activity countdowntimer

我正在编写锻炼应用程序,并尝试在Train活动中实施休息计时器。 CountDownTimer位于Train内,并在用户按下开始按钮时调用。

public CountDownTimer createTimer(long timerDuration) {

    Log.d("new timer duration:", "value: " + timerDuration);
    return new CountDownTimer(timerDuration, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            int progress = (int) (millisUntilFinished / 1000);
            secondsLeftOnTimer = progress;  // update variable for rest of app to access

            // Update the output text
            breakTimerOutput.setText(secondsToString(progress));
        }

        @Override
        public void onFinish() { // Play a beep on timer finish
            breakTimerOutput.setText(secondsToString(timerDurationSeconds));
            playAlertSound();  // TODO: Fix the delay before playing beep.
        }
    }.start();
}

只要用户停留在Train活动中,计时器就会起作用。如果你切换到另一个活动,计时器继续在后台运行(仍然会发出哔声),这就是我想要的。但是,如果您返回“培训”活动,则breakTimerOutput不再更新onTick TextView。

我怎样才能重新连接"当用户重新输入breakTimerOutput活动时,onTickTrain

Here is the full code for the activity, just in case.

1 个答案:

答案 0 :(得分:1)

我建议将计时器保留在Service内并使用BroadcastReceiver接收勾选以更新TextView中的TrainActivity

您需要从CountDownTimer开始Service。因此,在您onCreate的{​​{1}}方法中,您需要初始化Service

LocalBroadcastManager

因此,在计时器的每个刻度上(即broadcastManager = LocalBroadcastManager.getInstance(this); 方法),您可以考虑调用这样的函数。

onTick

现在在static final public String UPDATE_TIME = "UPDATE_TIME"; static final public String UPDATED_TIME = "UPDATED_TIME"; public void updateTextView(String time) { Intent intent = new Intent(UPDATE_TIME); if(time != null) intent.putExtra(UPDATED_TIME, time); broadcastManager.sendBroadcast(intent); } 创建一个TrainActivity

BroadcastReceiver

此外,您需要注册和取消注册public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.setContentView(R.layout.copa); receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String time = intent.getStringExtra(YourService.UPDATED_TIME); // Update your TextView here. } }; }

BroadcastReceiver