0

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.

Community
  • 1
  • 1
brandall
  • 6,094
  • 4
  • 49
  • 103

1 Answers1

1

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?

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 PackageManager and setComponentEnabledSetting() to disable your BOOT_COMPLETED BroadcastReceiver when 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, use setComponentEnabledSetting() again to re-enable the BOOT_COMPLETED BroadcastReceiver.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Fantastic, thank you. I'll read up on the setComponentEnabled setting and then return and mark your answer as correct. The loop I was concerned about was how often Android attempted to start the service if it was marked as enabled in the manifest despite any such attempt resulting in being cancelled by my app if userDisabled == true... – brandall Aug 19 '12 at 23:21
  • Works perfectly. A search on setComponentEnabledSetting() lead me to a previous answer of yours with sample code. I've updated the question and linked to it for anyone else that stumbles upon this question. Thanks again. – brandall Aug 20 '12 at 15:18