Is it a good practice to use TimerTask in OnHandleIntent in IntentService?

被刻印的时光 ゝ 提交于 2020-04-19 08:09:32

问题


i have an IntentService that calls webservice in OnHandleIntent every 45 seconds using TimerTask.

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?

my code is like this:

 @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

Thank you.


回答1:


Is it a good practice to use TimerTask in OnHandleIntent in IntentService?

Absolutely not.

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.

Please use a regular Service.

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?

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.

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.



来源:https://stackoverflow.com/questions/30216423/is-it-a-good-practice-to-use-timertask-in-onhandleintent-in-intentservice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!