I am using following code for GPS on/off.
//Enable GPS
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
context.sendBroadcast(intent);
//Disable GPS
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", false);
context.sendBroadcast(intent);
Programmatically I need to on/off GPS on android device. I am using above code for that. But It doesn't work on all the devices.
Open your phone's Settings app. Under "Personal," tap Location access. At the top of the screen, turn Access to my location on or off.
Add a TextView and a Button in the layout file. The TextView will display if the GPS is enabled or disabled upon the Button trigger.
Get current location settingsSettingsClient client = LocationServices. getSettingsClient(this); Task<LocationSettingsResponse> task = client. checkLocationSettings(builder.
In RESOLUTION_REQUIRED case, we ask user to give permissions, this is where we show the user prompt to enable GPS. Task<LocationSettingsResponse> result = LocationServices. getSettingsClient(getActivity()).
From my personal experience, I am answering this,
The hack code you shown in the your question has been stopped working from Android version 4.4. Your will fire this Exception starting from Kitkat version java.lang.SecurityException: Permission Denial: not allowed to send broadcast android.location.GPS_ENABLED_CHANGE
The First answer's code will not work any more, it only display animated GPS icon in notification bar.
For The security purpose Google developer has block above both methods which were previously working fine.
Hence conclusion is that You can not programmatically start GPS On or Off.
This code works on Rooted Phone
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] cmds = {"cd /system/bin" ,"settings put secure location_providers_allowed +gps"};
try {
Process p = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(p.getOutputStream());
for (String tmpCmd : cmds) {
os.writeBytes(tmpCmd + "\n");
}
os.writeBytes("exit\n");
os.flush();
}
catch (IOException e){
e.printStackTrace();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With