Service with AsyncTask

ε祈祈猫儿з 提交于 2019-12-07 12:32:25

问题


I have heard that it isnt good to have an async task in a service.

Is it really necessary for an AsyncTask or just onStartCommand()?

I am wondering because I have a Service with an AsyncTask that is launched by an alarm. And it launches the Service more than once; it's only supposed to launch once.

Could this be the reason?

EDIT:

Here is how i set up the alarm.

    String alarm = Context.ALARM_SERVICE;

    AlarmManager am = (AlarmManager)getSystemService(alarm);

    Intent Aintent = new Intent("REFRESH_THIS");
    PendingIntent pi = PendingIntent.getBroadcast(this, 0, Aintent, 0);
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.HOUR_OF_DAY, 9);
    calendar.add(Calendar.MINUTE, 0);
    calendar.add(Calendar.SECOND, 0);
    calendar.add(Calendar.MILLISECOND, 0);

    am.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis() , AlarmManager.INTERVAL_DAY, pi);

回答1:


If you have a long-running operation in a service, consider using IntentService, it will launch and manage a background thread for you. And it has the added benefit that it shuts itself down when finished automatically. You could achieve something similar with an AsyncTask, but an IntentService will do the right thing.

As for your other question, the service being launched multiple times has nothing to do with the AsyncTask. If your alarm runs multiple times, it will launch multiple instances of your service. There is, AFAIK, really no way to make a singleton service automatically. You could check if it's running before launching, or set a preferences flag (error prone), but the preferred way is to have short-lived services launched every time you need to do something, and shut themselves when done. IntentService fits this pattern nicely.




回答2:


There is no bad thing if you want to use AsyncTask in service. It is good if you are using asynctask in service because service runs on Main Thread so that if you are using long process from service it can slow your UI.

You can also create Thread and work in that.




回答3:


There is a way to having more control around threads and tasks, specially if you need to perform different ones in a certain order. There is a nice approach to manage the whole system by using queues, thread pool executors, runnables/callables and a service. http://ugiagonzalez.com/2012/07/02/theres-life-after-asynctasks-in-android/



来源:https://stackoverflow.com/questions/7577624/service-with-asynctask

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