计时器任务无限期的机器人后,停止运行 [英] Timer Task stops running after indefinite time in android
问题描述
我在Android的一个新手。我开发中一个特定的一块code执行后,我使用的是服务与定时器中有一个计时器任务每5秒background.To做到这一点的应用程序。对于一段时间它工作正常,但我的服务正在运行,经过一段不确定的,但计时器任务的机器人自动停止。这是我的code,请帮助。先谢谢了。
公共无效ONSTART(意向意图,诠释startid){
//这是code为我服务类ONSTART
INT延迟= 1000; //延迟1秒。
最终诠释周期= 5000; //重复5秒。
定时器=新的Timer();
timer.schedule(新的TimerTask(){
@覆盖
公共无效的run(){
执行code();
},延迟,周期);
};
在我看来,你应该使用AlarmManager与IntentService安排重复背景的任务,而不是定时任务。 A定时器是不可靠的,并不总是在Android框架内正常工作。另外,如果手机是睡着了一个定时器将不会执行。你可以有警报唤醒手机来执行你的code与AlarmManager。
请参阅:
<一个href="https://developer.android.com/reference/android/app/AlarmManager.html">https://developer.android.com/reference/android/app/AlarmManager.html
<一个href="http://mobile.tutsplus.com/tutorials/android/android-fundamentals-scheduling-recurring-tasks/">http://mobile.tutsplus.com/tutorials/android/android-fundamentals-scheduling-recurring-tasks/
<一个href="http://android-er.blogspot.in/2010/10/simple-example-of-alarm-service-using.html">http://android-er.blogspot.in/2010/10/simple-example-of-alarm-service-using.html
在手机的情况下重启,您将需要再次触发报警经理。请参见本教程关于如何做到这一点的确切说明:
<一个href="http://www.androidenea.com/2009/09/starting-android-service-after-boot.html">http://www.androidenea.com/2009/09/starting-android-service-after-boot.html
I am a newbie in android. I am developing an app in which a particular piece of code executes after every 5 seconds in background.To achieve this I am using a service with timer with a timer task in it. For sometime its working fine but after some indefinite my service is running but timer task stops automatically in android. Here is my code please help. Thanks in advance.
public void onStart(Intent intent, int startid) {
//this is the code for my onStart in service class
int delay = 1000; // delay for 1 sec.
final int period = 5000; // repeat 5 sec.
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
executeCode();
}, delay, period);
};
In my opinion, you should use AlarmManager with an IntentService to schedule repeating background tasks instead of Timer tasks. A Timer is unreliable and doesn't always work correctly within the Android Framework. Also, a Timer won't execute if the phone is asleep. You can have alarms wake up the phone to execute your code with AlarmManager.
See:
https://developer.android.com/reference/android/app/AlarmManager.html
http://mobile.tutsplus.com/tutorials/android/android-fundamentals-scheduling-recurring-tasks/
http://android-er.blogspot.in/2010/10/simple-example-of-alarm-service-using.html
In case of phone restart, you will need to trigger the alarm manager again. See this tutorial for exact instructions on how to do this:
http://www.androidenea.com/2009/09/starting-android-service-after-boot.html
这篇关于计时器任务无限期的机器人后,停止运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!