[英]Count times in service with worker thread in Android
发生特殊事件时,我想开始计算服务时间。 我想在工作线程中执行此操作。
甚至使用CountDownTimer()
都能为我做到这一点。
问题是,当我在IntentService
类的OnHandleIntent()
中使用此方法时,出现错误:
java.lang.IllegalStateException: Handler (android.os.CountDownTimer$1) {235e78c} sending message to a Handler on a dead thread
。
这是计时和在到达目的地时做特别工作的最佳方法吗? 如果没有,我该怎么办? 如果是,如何解决? 谢谢。
我的服务代码是:
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.os.CountDownTimer;
import android.os.Environment;
import android.util.Log;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
public class TimeService extends IntentService {
public TimeService(){
super("");
}
@Override
protected void onHandleIntent(Intent intent) {
new CountDownTimer(20000,1000){
@Override
public void onTick(long millisUntilFinished) {
System.out.println("Time remaining: "+millisUntilFinished/1000);
}
@Override
public void onFinish() {
System.out.println("done");
}
}.start();
}
}
Trying using your countdown timer in Service class as
CountDownTimer countDownTimerVariable;
In @Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
// based on your condition
if(condition)
{
performCountDown();
}
}
public void performCountDown()
{
countDownTimerVariable = new CountDownTimer(remainingMillisForCountDown, 1000) {
@Override
public void onFinish() {
//Action for when the timer has finished.
Log.i("timer finish", "finished");
}
@Override
public void onTick(long millisUntilFinished) {
//Action for every tick of the countdown.
// timeCalculate((millisUntilFinished / 1000));
Log.i("timer finish", "finished" + (millisUntilFinished / 1000) + " Countdown");
}
};
countDownTimerVariable.start();
}
and in destroy of service
@Override
public void onDestroy() {
// TODO Auto-generated method stub
this.unregisterReceiver(notifyServiceReceiver);
super.onDestroy();
if(countDownTimerVariable != null)
countDownTimerVariable.cancel();
}
我不建议您使用IntentService。 您应该使用常规服务。
当Intent服务启动时,它会创建一个新的工作线程,当他们的任务完成时,它将终止。 但是在您的情况下,您使用的是Countdowntimer,它在工作线程终止后运行,因此会引发异常。
您可以尝试一种解决方案:
protected void onHandleIntent(Intent intent) {
Looper.prepare();
new CountDownTimer(20000,1000){
@Override
public void onTick(long millisUntilFinished) {
System.out.println("Time remaining: "+millisUntilFinished/1000);
}
@Override
public void onFinish() {
System.out.println("done");
Looper.myLooper().quit();
}
}.start();
Looper.loop() ;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.