I have seen many android Service examples where return START_STICKY is used to start an app on boot but is there anyway I can use the same for IntentService. I understand that Service method runs on the main UI thread and the IntentService as a separate thread.
But how exactly can they be invoked and why is it not possible to start IntentService on boot. Since IntentService runs on a separate thread we have more control over it if i'm not worng.
I tried using onStartCommand in IntentService but my app crashes on boot even though it works perfectly fine when started manually. Can we override onStartCommand in IntentService ?
Can someone help me with this ?
START_STICKY means the system will eventually restart your Service after it has been killed by the system. When it gets restarted, the Intent parameter to onStartCommand() will be null. This lets you detect when you get restarted as the Intent will otherwise be the one you passed to startService().
Limitations / DrawbacksThe Service may block the Main Thread of the application. The IntentService cannot run tasks in parallel. Hence all the consecutive intents will go into the message queue for the worker thread and will execute sequentially.
Provided since Android API 3, the purpose of IntentService was to allow asynchronous tasks to be performed without blocking the main thread. The deprecation is one of a number of steps introduced starting with Android 8.0 (API 26) to limit the actions that can be performed while an app is in the background.
Running at boot and START_STICKY
have nothing to do with one another - START_STICKY
is a flag to determine what should happen if your service is killed by Android.
IntentService
is designed to process an incoming intent (via handleIntent
) and stop immediately after. As seen in the source of IntentService, it already handles onStartCommand
appropriately.
As long as you are requesting
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
and have the correct intent-filter on your IntentService
:
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
Then your service will get called on boot complete.
(The one exception is if your app is installed on an SD card as per install location)
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