离开和返回后用计时器 onTick 更新 TextView activity

Updating TextView with timer onTick after leaving and returning to activity

我正在编写一个锻炼应用程序,并试图在 Train activity 中实现一个休息计时器。 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 activity 中,计时器就会工作。如果你切换到另一个activity,定时器在后台继续运行(蜂鸣声仍然出现),这就是我想要的。但是,如果您返回火车 activity,breakTimerOutput TextView 不再由 onTick 更新。

如何在用户重新输入Trainactivity时"reconnect"breakTimerOutputonTick

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

我想建议将计时器放在 Service 中,并使用 BroadcastReceiver 接收滴答以更新 TrainActivity 中的 TextView

您需要从 Service 开始 CountDownTimer。所以在你的ServiceonCreate方法中你需要初始化一个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

@Override
protected void onStart() {
    super.onStart();
    LocalBroadcastManager.getInstance(this).registerReceiver((receiver), 
        new IntentFilter(YourService.UPDATE_TIME)
    );
}

@Override
protected void onStop() {
    LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
    super.onStop();
}