質問

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();
}
役に立ちましたか?

解決

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();
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top