调用cancel()后重启计时器

时间:2011-11-09 07:23:17

标签: android timer restart onresume

我需要在onResume()上重新启动计时器,因为在onPause()我致电timer.cancel()。我怎么能这样做?

以下是我启动计时器的代码:

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

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


                    }
                });

            }

        }, 300, 30000);

在这里我取消了计时器:

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

1 个答案:

答案 0 :(得分:1)

试试这样:

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