Search code examples
androidtimerrestartonresume

Restart a timer after calling cancel()


I need to restart a timer on onResume() because on onPause() I call timer.cancel(). How can I do this?

Here is the code where I start the timer :

 handler = new Handler();
        t = new Timer();
        t.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {

                runOnUiThread(new Runnable() {
                    public void run() {
                        doReload2();
                        populate();


                    }
                });

            }

        }, 300, 30000);

and here I cancel the timer :

@Override
protected void onPause() {
    super.onPause();
    System.out.println("onPause!!!!!!");
    t.cancel();
}

Solution

  • Try like this:

    Timer t;
    
    @Override
    void onCreate(){
        t = Timer();
    } 
    
    @Override
    void onResume(){
        super.onResume();
        t.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    public void run() {
                        doReload2();
                        populate();
                    }
                });
            }
        }, 300, 30000);
    }
    
    @Override
    void onPause(){
        super.onPause();
        System.out.println("onPause!!!!!!");
        t.cancel();
    }