My Android application is a foreground service and I would like the option of the user being able to disable the service whenever they like, without having to uninstall the entire application.
I use the enabled = true label in the manifest and boot completed to start the service in the foreground. My concern is that should I have a very basic global boolean value (inside onCreate of the service) of userEnabled = false to prevent the service from starting (stopSelf), Android will continue to attempt to start my service which will result in a loop and therefore use unnecessary resource?
Please can someone share their knowledge with me to let me know that I either don’t have to be concerned about this, or the correct procedure/method by which to do this? I can’t find any documentation or posts that give direction.
I thank you in advance.
Answer: Please see CommonsWare’s answer below and here is a link to some useful code, also by CommonsWare
After further reading, there is no loop that can be caused by having the service set enabled true in the Manifest.
That sentence did not completely parse for me — I fail to see the loop that you are worried about.
That being said, if you wish the user to control whether or not your service starts up at boot time, use
PackageManagerandsetComponentEnabledSetting()to disable yourBOOT_COMPLETEDBroadcastReceiverwhen the user disables your service. That way, on a reboot, you will not get control and therefore will not start the service. If the user re-enables your service, usesetComponentEnabledSetting()again to re-enable theBOOT_COMPLETEDBroadcastReceiver.