Sometimes in my apps I need to do something in the background repeatedly (every X hours).
Up to API 25 i use:
AlarmManager
with setInexactRepeating (to respect battery)WakefulBroadcastReceiver
to have enough times to do all worksIntentService
to do all in background threadOn API 26 all of this are deprecated or limited and are suggested to use JobScheduler
with JobService
instead.
The problem is that JobService
run in main thread.
I think to use AsyncTask
inside JobService
and call JobService.jobFinished
inside onPostExecute
this is the correct way to do this?
You can use JobIntentService of support library 26 which has the exact workflow of IntentService. For pre Oreo devices, JobIntentService will use old IntentService. JobIntentService class relies on JobScheduler API of android.
For more, https://developer.android.com/reference/android/support/v4/app/JobIntentService.html
On API 26 all of this are deprecated or limited
AlarmManager
did not change in Android 8.0, IIRC. IntentService
did not change in Android 8.0 either. However, you would need to make the IntentService
be a foreground service and use a getForegroundService()
PendingIntent
.
The problem is that JobIntentService run in main thread.
onHandleWork()
is called on a background thread, both for Android 8.0+ and pre-8.0 devices. I used this sample app of mine, adding logging statements to log the current thread ID inside enqueueWork()
(called on the main application thread) and onHandleWork()
. They are different thread IDs, and hence they are different threads.
this is the correct way to do this?
No, just do your work in onHandleWork()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With