1
使用textView和開始/停止按鈕的基本倒計時應用程序。 如果我在countDownTimer正在運行時關閉應用程序,它將繼續工作直到完成。問題是,當我重新打開應用程序時,它正在倒計時onTick()方法不更新TextView的新實例。 有沒有辦法讓這項工作?Android CountDownTimer - onTick()在重新打開應用程序後不更新用戶界面
如果我理解正確CountDownTimer運行在它自己的服務。 我的代碼:
public class MainActivity extends AppCompatActivity {
TextView display;
Button button;
MyCountdownTimer myTimer;
long starTime = 15 * 1000;
long interval = 1000;
boolean timerIsStarted = false;
private static final String TAG = "LogMainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myTimer = new MyCountdownTimer(starTime, interval);
display = (TextView) findViewById(R.id.textViewID);
button = (Button) findViewById(R.id.buttonID);
}
public void startButtonOnClick(View view) {
if(!timerIsStarted){
timerIsStarted = true;
myTimer.start();
} else {
timerIsStarted = false;
display.setText("00");
myTimer.cancel();
}
}
public class MyCountdownTimer extends CountDownTimer {
public MyCountdownTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onTick(long millisUntilFinished) {
Log.d(TAG, String.valueOf(millisUntilFinished));
display.setText(String.valueOf(TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished)));
}
@Override
public void onFinish() {
timerIsStarted = false;
Log.d(TAG, "Finished!");
Toast.makeText(getApplicationContext(), "Finished!", Toast.LENGTH_SHORT).show();
display.setText("Finished!");
}
}
}
@diogojme把這個答案! :) – petey
@petey我已經做到了 – diogojme