开发者

Service with AsyncTask

开发者 https://www.devze.com 2023-04-07 22:40 出处:网络
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 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);

 开发者_如何学C   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);


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.


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.


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/

0

精彩评论

暂无评论...
验证码 换一张
取 消