问题描述
我有一个IntentService,它使用TimerTask每45秒在OnHandleIntent中调用一次Webservice.
i have an IntentService that calls webservice in OnHandleIntent every 45 seconds using TimerTask.
我的问题是:我正在调用应用程序启动IntentService,在OnHandleIntent中,由于TimerTask而使任务不断重复..这样做是一种好习惯还是有任何弊端?我应该在活动中使用警报管理器在任何时间调用意图服务,还是可以继续使用计时器任务在OnHandleIntent中取消该任务?
my question is:i am calling on app start the IntentService, and in OnHandleIntent the task keeps repeating due to TimerTask..is it a good practice to do this or does this have any drawbacks? should i use an alarm manager in my activity to call the intent service every amount of time or its fine to keep on repeaing the task in OnHandleIntent using the timer task?
我的代码是这样的:
@Override
protected void onHandleIntent(Intent intent)
{
context=this; //INTENT CONTEXT
final int timerValue = Integer.parseInt(MainActivitySharedPref.GetValue(context, "serviceTimer"));
Log.d(TAG, "DOWNLOADSERVICE called having MainActivity.callService as: " + MainActivity.callService);
t = new Timer();
task = new TimerTask()
{
public void run() {
//run tasks
};
t.scheduleAtFixedRate(task, 0, timerValue); // service executes task every 45 seconds
谢谢.
推荐答案
绝对不是.
IntentService
旨在允许您通过onHandleIntent()
在提供的后台线程中执行工作.它不是设计用于派生线程,注册侦听器,设置TimerTask
/ScheduledExecutorService
或执行可能会超出onHandleIntent()
末尾的其他任何操作的设计. IntentService
将在onHandleIntent()
结束后自行关闭,此后,Android可能会在几秒钟内终止后台进程(在本例中为TimerTask
)可以正常工作之前终止您的进程.
IntentService
is designed to allow you to perform work in a supplied background thread via onHandleIntent()
. It is not designed for you to fork threads, register listeners, set up TimerTask
/ScheduledExecutorService
, or do anything else that would be running past the end of onHandleIntent()
. The IntentService
will shut itself down once onHandleIntent()
ends, after which Android may terminate your process within seconds, before your background threads (or, in this case, TimerTask
) can do its work.
请使用常规的Service
.
如果仅当您的某些活动处于前台时才执行此操作,则每隔45秒就可以了.如果您尝试连续执行此操作,请在电池供电的设备上做好准备,以防用户因造成电池耗尽而受到攻击.
If you are doing this only while some activity of yours is in the foreground, the every-45-seconds part is OK. If you are trying to do this continuously, on battery-powered devices, be prepared to be attacked by users for the battery drain that you are causing.
但是,当您的活动处于前台时...常规Service
中的ScheduledExecutorService
(现代替代TimerTask
)应该没问题.不需要AlarmManager
,它专门用于在进程终止后为您提供控制权,从而可以延长轮询时间.
But, while an activity of yours is in the foreground... ScheduledExecutorService
(the modern replacement for TimerTask
) in a regular Service
should be fine. You should not need AlarmManager
, which is specifically designed to give you control after your process has been terminated, for longer polling periods.
这篇关于在IntentService的OnHandleIntent中使用TimerTask是一种好习惯吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!