无法启动计时器在Android的服务计时器、无法启动、Android

2023-09-07 13:21:38 作者:儍儍de豬々

我不知道什么是错回事......我不能够启动一个定时器在我的服务。继code

I dont know whats wrong going on... I am not able to start a timer in my service. Following the code

public class BkgService extends Service{

private Timer ServUpdTimer = new Timer();
private static  long TMR_INTERVAL = 10*60*1000;

public void onCreate() {
    super.onCreate();
    StartServUpdateTask();
    }

private void StartServUpdateTask() {

        if(ServUpdTimer != null)
            ServUpdTimer.cancel();


        ServUpdTimer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
            }
        }, 0, TMR_INTERVAL);
    }
}

但是,当我到达行 ServUpdTimer.scheduleAtFixedRate()我收到以下异常

03-03 23:32:14.851:E / AndroidRuntime(6083):   java.lang.RuntimeException的:无法启动服务   mt.android.app.BkgService@40544838意图{   CMP = mt.android.app / .BkgService}:java.lang.IllegalStateException:   定时器被取消

03-03 23:32:14.851: E/AndroidRuntime(6083): java.lang.RuntimeException: Unable to start service mt.android.app.BkgService@40544838 with Intent { cmp=mt.android.app/.BkgService }: java.lang.IllegalStateException: Timer was canceled

我会很感激,如果有人可以抛出一些光在这...

I would be very grateful if someone can throw some light on this...

推荐答案

从Javadoc文档 Timer.cancel()

From the Javadoc for Timer.cancel():

在一个计时器已终止,它的执行线程终止摆好,并且没有更多的任务可以调度它。

Once a timer has been terminated, its execution thread terminates gracefully, and no more tasks may be scheduled on it.

从Javadoc文档 Timer.scheduleAtFixedRate()

From the Javadoc for Timer.scheduleAtFixedRate():

抛出:IllegalStateException - 如果任务已经安排或取消,计时器被取消,或者计时器线程已终止

android 计时器

Throws: IllegalStateException - if task was already scheduled or cancelled, timer was cancelled, or timer thread terminated.

定时器被立即取消:您需要创建一个新的实例:

The Timer is cancelled immediately: you need to create a new instance:

private void StartServUpdateTask() {

    if(ServUpdTimer != null)
    {
        ServUpdTimer.cancel();
    }
    ServUpdTimer = new Timer();

    ...
}
 
精彩推荐
图片推荐