I use an AlarmManager
to run a Service which tries to download a file from the web. If it fails I'd like to retry that Service in 5 minutes.
Inside the Service I run an AsyncTask
to run my code. As far as I know the only way I can tell if it failed or not is from the onPostExecute()
.
What is the best way of implementing a retry of that Service again?
Falmarri's answer is the correct one, and I do not understand your concerns.
In
onPostExecute()
, when you determine that things went awry:getSystemService(ALARM_SERVICE)
to get theAlarmManager
set()
on theAlarmManager
to trigger you in 5 minutesIf needed, use extras on the
Intent
in thePendingIntent
to give you information about what to retry, or use a custom action string to distinguish retries from the scheduled alarm, or something. Note that if you useIntent
extras, you will need to choose an appropriate flag withPendingIntent
(e.g.,FLAG_UPDATE_CURRENT
).So? Multiple classes can talk to the
AlarmManager
. Also, feel free to pass data to yourAsyncTask
subclass via its constructor.Also, you might want to consider using an
IntentService
rather than aService
andAsyncTask
.IntentService
gives you a background thread automatically. Plus, it shuts down when there is no more work to be done, which is also important, so you don't get a bunch of one-star ratings on the Market complaining about the service you keep running all of the time.Why not?
Of course. That's what you want. It matters not a whit whether the
Service
or theAsyncTask
or theMyOtherReallyCoolClass
is the one actually talking toAlarmManager
-- the component that is rescheduling theService
is theService
itself.