Pause and Resume timer made using handlers

2019-06-01 19:01发布

问题:

Here is my code for an activity. In this I am printing the time elapsed on a text view. I want to put onPause and onResume method in this. It should work such that the time is paused while app is in background . And when again brought to forefront, should timer start from where it paused. I tried it using this code but the time is not paused. It continues to run in background. Can anybody help to find workaround for this.

package com.example.test;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class MainActivity extends Activity {
    TextView tt1;
    private Handler customHandler = new Handler();
    long timeInMilliseconds = 0L,timeToGo=0L,startTime=0L;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tt1=(TextView) findViewById(R.id.textView1);
        startTime=System.currentTimeMillis();
        customHandler.postDelayed(updateTimerThread, 0);
    }
    public Runnable updateTimerThread=new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            long timeNow = System.currentTimeMillis();
            timeToGo = 30 - (timeNow - startTime) / 1000;
            tt1=(TextView) findViewById(R.id.textView1);
            tt1.setText(timeToGo+"");
            if(timeToGo<0L){
                Intent intent=new Intent(MainActivity.this,Game.class);
                finish();
                startActivity(intent);
                }
            else
                customHandler.postDelayed(this, 0);
        }
    };
    @Override
    public void onPause() {
        super.onPause();
        customHandler.removeCallbacksAndMessages(null);
    }
    @Override
    public void onResume() {
        super.onResume();  // Always call the superclass method first
        customHandler.postDelayed(updateTimerThread, 0);
     }
 }

回答1:

You need to update your startTime in onResume cause it hasn't changed...

@Override
public void onResume() {
    startTime = System.currenTimeMillis() - timeToGo * 1000;
    ...
}

Or just use a Chronometer class http://developer.android.com/reference/android/widget/Chronometer.html



回答2:

   @Override
   protected void onPause() {     
                customHandler.removeCallbacks(updateTimerThread);
               super.onPause(); }