簡體   English   中英

如何使用在后台運行的計數器的當前值更新Activity的TextView?

[英]How to update the TextView of an Activity with the current value of a counter running in the background?

我有一個計數器,每1秒鍾增加1,在TextView中顯示其當前值。

在Activity被銷毀然后重新創建之前,一切工作正常。 在這些情況下,計數器將重置為0。

我已經讀過我必須將計數器的代碼放入自定義Service中 ,以便使其在后台執行。 然后,我應該將我的Activity(包含TextView)與BroadcastServicer進行通信

我已經關注了一些有關BroadcastReceivers的教程,但仍然不知道如何解決此問題。

您能否向我展示將BroadCastReceiver與服務進行通信以便更新Activity中的TextView的正確方法?

到目前為止,這是我的活動代碼:

public class CounterActivity extends Activity{
    private long startTime = 0;
    private Handler h = new Handler();
    private TextView tvCounter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task_list);
        tvCounter = (TextView)findViewById(R.id.tvCounter);

        Runnable run = new Runnable() {

            @Override
            public void run() {
               long millis = System.currentTimeMillis() - startTime;
               int seconds = (int) (millis / 1000);
               int minutes = seconds / 60;
               seconds     = seconds % 60;

               tvCounter.setText(String.format("%d:%02d", minutes, seconds));

               h.postDelayed(this, 500);
            }
        };

        startTime = System.currentTimeMillis();
        h.postDelayed(run, 0);
    }

}

提前致謝!

考慮使用異步任務和處理程序來更新UI組件

您可以使用下面的代碼保存startTime,計數器不會重置〜

protected void onSaveInstanceState(Bundle icicle) {
  super.onSaveInstanceState(icicle);
  icicle.putLong("starttime", startTime);
}

public void onCreate(Bundle savedInstanceState) {
  if (savedInstanceState != null){
     startTime = savedInstanceState.getLong("starttime");
  }else{
     startTime = System.currentTimeMillis();
  }
}

暫無
暫無

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

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