无法启动计时器在Android的服务 [英] Unable to start the timer in a service in android

查看:104
本文介绍了无法启动计时器在Android的服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道什么是错回事......我不能够启动一个定时器在我的服务。继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 - 如果任务已经安排或取消,计时器被取消,或者计时器线程已终止

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

    ...
}

这篇关于无法启动计时器在Android的服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆