0

你好我正在android中创建一个服务。在服务中,我希望我的代码每 5 分钟定期运行一次。我使用相同的线程。

下面是我的代码

@Override
public void onCreate() {
    super.onCreate();
    Toast.makeText(this, "Service created ...", Toast.LENGTH_LONG).show();

    Thread thr = new Thread() {
    public void run() {
        try {
            sleep(20000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally{}
        }
   };
    while (true) {

        // Some code1

        thr.start();
        while(thr.isAlive()){}

        //some code 2
    }

}

我收到以下错误

09-24 21:34:40.869:E/AndroidRuntime(12393):致命异常:主要 09-24 21:34:40.869:E/AndroidRuntime(12393):java.lang.RuntimeException:无法创建服务 com.example。 find.your.friend.iith.updateService: java.lang.IllegalThreadStateException: 线程已经启动。

你能告诉我我哪里错了吗?

4

2 回答 2

0

您无法启动已经存在的线程。作为while(true)永远执行,thr.start()被一次又一次地调用。尝试:

while (true) {

    // Some code1

    if(!thr.isAlive()) {
        thr.start();
    }
    while(thr.isAlive()){}

    //some code 2
}
于 2012-09-24T16:16:02.713 回答
0

为什么不使用报警服务?它是您问题的最佳解决方案。

于 2012-09-24T17:22:02.710 回答