I know that the question about turning on/off GPS programatically on android has been discussed many times, and the answer is always the same:
"You can't for security/privacy reasons, you have to forward to location preferences screen and let the user enable/disable it."
I understand that, however I recently bought Tasker from the market and, among many other things that you can accomplish with it, you can set rules to auto-enable GPS on entering pre-determined applications and disable it on exit (see here for the tutorial on how to do it, and it just works!) and this app can't be signed with the firmware signing key as it works on many android versions and different devices and you don't even need to be rooted.
I would like to do this in my app. Of course, I don't want to blow up the users privacy, so I would first ask the user if he wants to turn it on automatically with the typical "remember my decision" checkbox and if he answers yes, enable it.
Does anybody have any idea or clue on how Tasker achieves this?
ENABLE GPS:
DISABLE GPS:
Since Android version 4.4, you can't enable/disable gps programatically. If you try the code proposed on this answer, an exception will be fired.
Maybe with reflection tricks around the class
android.server.LocationManagerService
.Also, there is a method (since API 8)
android.provider.Settings.Secure.setLocationProviderEnabled
the GPS can be toggled by exploiting a bug in the power manager widget. see this xda thread for discussion.
here's some example code i use
use the following to test if the existing version of the power control widget is one which will allow you to toggle the gps.
To turn GPS on or off programatically you need 'root' access and BusyBox installed. Even with those, the task is not trivial.
Sample's here: Google Drive, Github, Sourceforge
Tested with 2.3.5 and 4.1.2 Androids.
This code works on ROOTED phones if the app is moved to
/system/aps
, and they have the following permissions in the manifest:Code