[英]Cancel a CountDownTimer in another activity
我在一項活動中有一個 CountDownTimer,需要在另一項活動中取消。 我遇到的問題是,即使我在另一個活動中調用 endTestTimer() 方法,CountDownTimer 也沒有被取消。 這是 CountDownTimer 的代碼:
private long testMillisLeft, questionMillisLeft;
private static CountDownTimer testTimer;
private void startTestTimer()
{
long startTime = DataHolder.getTestTime()*1000; //getTestTime() is the seconds
testTimer = new CountDownTimer(startTime, 1000) {
@Override
public void onTick(long millisUntilFinished) {
testMillisLeft = millisUntilFinished;
updateTestTimeLeft();
}
@Override
public void onFinish() {
Intent intent = new Intent(MainActivity4.this, MainActivity5.class);
startActivity(intent);
}
}.start();
}
public static void endTestTimer()
{
if(testTimer != null)
{
testTimer.cancel();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);
testTimeLeft = (TextView) findViewById(R.id.testTimerTextView);
mathProblem = (TextView) findViewById(R.id.mathProblemTextView);
testTimer = null;
startTestTimer();
}
這是我試圖在另一個活動中取消相同計時器的方式:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MainActivity4.endTestTimer();
}
對此相關帖子的評論說 static CountDownTimer 會造成 memory 泄漏。 如果是這種情況,我如何在另一個活動中調用 endTestTimer() 方法並讓它取消計時器? 或者,如果它不能是 static,我如何直接訪問 testTimer CountDownTimer 並在另一個活動中調用它。
調查 Android 生命周期讓我看到了這篇文章和這篇文章,我發現這兩篇文章都非常有幫助。 據我了解,當用戶點擊后退按鈕時,會為當前顯示的活動調用 onDestroy() 方法,然后為要顯示的活動調用 onCreate() 方法。 因此,為了取消 MainActivity4 上的計時器(在我的例子中是當前活動),我將此代碼添加到其 class 文件中:
@Override
protected void onDestroy() {
testTimer.cancel();
questionTimer.cancel();
super.onDestroy();
}
現在,當用戶退出 MainActivity4(不管其他活動將他們帶到什么活動)並自動調用 onDestroy() 時,兩個計時器都被取消,然后 MainActivity4 被銷毀。 這對我來說似乎很好,但我不確定這樣做是否有任何缺點,所以請告訴我是否有。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.