I am building a Lost Device Finder app and want to be able to turn on GPS
programmatically.
I am able to get Modify System Settings permission, but when I try to turn on GPS
, Permission Denied exception is thrown.
The following is my Code:-
if (!Settings.System.canWrite(getBaseContext())) {
startActivityForResult(new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS).setData(Uri.parse(String.format("package:%s", getPackageName()))), request_code);
}
else{
turnGpsOn(getBaseContext());
}
private void turnGpsOn (Context context) {
String beforeEnable = Settings.Secure.getString(context.getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
String newSet = String.format ("%s,%s",
beforeEnable,
LocationManager.GPS_PROVIDER);
try {
Settings.Secure.putString (context.getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
newSet);
} catch(Exception e) {}
}
And I have defined permissions in Manifest like this,
<uses-permission android:name="android.permission.WRITE_SETTINGS"
tools:ignore="ProtectedPermissions" />
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS"
tools:ignore="ProtectedPermissions" />
My device is not rooted but I think it can be done as the "PowerShade" app requires Modify System Settings Permission in order to do it.