Lucas
Lucas

Reputation: 1279

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

I have a counter that increases by 1 every 1 second displaying its current value in a TextView.

Everything works fine until the Activity is destroyed and then recreated. In those cases, the counter resets to 0.

I have read that I must put the code of the counter inside a custom Service, so it gets executed in the background. Then, I should comunicate my Activity (which contains the TextView) with a BroadcastServicer.

I have followed a few tutorials about BroadcastReceivers but still I don't get how to solve this problem.

Could you please show me the right way to comunicate the BroadCastReceiver with the Service in order to update the TextView inside the Activity?.

This is my code of my Activity so far:

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);
    }

}

Thanks in advance!

Upvotes: 0

Views: 102

Answers (2)

Bolton
Bolton

Reputation: 2256

You could save your startTime using code below , then counter will not reset~

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();
  }
}

Upvotes: 2

Muhannad A.Alhariri
Muhannad A.Alhariri

Reputation: 3912

consider using Async task and handlers to update UI components

Upvotes: 2

Related Questions