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);
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 anIntentServicewill 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.IntentServicefits this pattern nicely.