Luckily #2 (foreground tracking) is easier to achieve than #3, so that's a good problem to have.
But there are a few different things going on that are could be complicating the issue:
When an app wants to track GPS (and the app uses background tracking), android will give the user these runtime permission options:
- Don't allow tracking at all
- Only allow tracking when app is in foreground
- Allow tracking in background
The service in the example you posted should be able to be used for both background and foreground tracking (if the user granted background tracking).
So, are you saying that if the user selects "Only allow tracking when app is in foreground", that the service (in the example) is not properly running?
Also when you say "How can I turn off the service Attribute programmtically so that the user can turn off background tracking but still have tracking whilst the app is active?" that makes me think that you might be thinking that the service is only needed for background tracking. This I believe is not true. The service can run when the app is in the foreground and when the app goes to background android will simply not allow your app to get GPS info in the background if the user denied that runtime permission. So basically, you need the service in the example to run regardless if the app is running in the foreground or background.