簡體   English   中英

當我從我的應用程序中按下后退按鈕時,Countdowntimer 如何繼續在后台運行?

[英]How Countdowntimer continue Running in the background when i press back button from my application?

我的計時器代碼是:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    initializer();
    fire.setOnClickListener(this);
}

private void initializer() {

    minute = (EditText) findViewById(R.id.etMinute);
    seconds = (EditText) findViewById(R.id.etSeconds);
    fire = (Button) findViewById(R.id.bFireTimer);
    Remain=(TextView)findViewById(R.id.tvRemain);
}



@Override
public void onClick(View v) {
    switch (v.getId()) {

    case R.id.bFireTimer:

                min=minute.getText().toString();
                sec=seconds.getText().toString();
                int MIN= Integer.parseInt(min);
                int SEC=Integer.parseInt(sec);
                long TIME= (MIN*60)+SEC;
                timercount =  new MyCount(TIME * 1000, 1000);
                timercount.start();


        break;
    }

}

public class MyCount extends CountDownTimer {

     public MyCount(long millisInFuture, long countDownInterval) {
          super(millisInFuture, countDownInterval);
      }

      @Override
      public void onFinish() {
          //some script here
      }

      @Override
      public void onTick(long millisUntilFinished) {

       //some  script here 
         int remseconds=(int)millisUntilFinished/1000;
        int remminuts=remseconds/60;
            remseconds= remseconds%60;
            remminuts= remminuts%60;
            Remain.setText(String.format("%d : %02d" , remminuts,remseconds));



         // Remain.setText(""+millisUntilFinished);


      }   }

當我以分鍾和秒為單位輸入並按下啟動按鈕時,計時器將啟動。但是當我退出我的應用程序時,計時器不會繼續在后台運行。我想在退出我的應用程序時繼續運行計時器,並且當我啟動我的應用程序時,我看到正在運行的計時器..plz 我需要幫助才能做到這一點..在此先感謝。

做你想做的最簡單的方法是在你的活動停止時保存當前系統時間。 當它再次恢復時,只需檢查它經過了多長時間並相應地更新計時器。 獲取當前時間使用

System.currentTimeMillis();

有一個 long 成員變量,它在 onStop 中取當前時間的值。 確保它也保存在 onSaveInstanceState 中並在 onRestoreInstanceState 中恢復。 進入 onResume 后,必須將計時器值設置為舊值 + (currentTime - savedTime)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM