0

I know that the question about turning on/off GPS programmatically on android has been discussed many times. I have the same question that has been discussed in this link:

How can I enable or disable the GPS programmatically on Android?

But is there a way that works for android 6.x?

Community
  • 1
  • 1
N.N.H
  • 11
  • 1
  • 1
  • 2

2 Answers2

0

First you need get runtime permission for gps then this will work

Please check this link to enable and disable directly gps

https://stackoverflow.com/a/33555732

Community
  • 1
  • 1
Ratnesh
  • 65
  • 9
0
private void buildAlertMessageNoGps() {
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage(" Your GPS seems to be disabled, do you want to enable it?")
            .setCancelable(false)
            .setPositiveButton("ّyes", new DialogInterface.OnClickListener() {
                public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                    startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                }
            })
            .setNegativeButton("no", new DialogInterface.OnClickListener() {
                public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                    dialog.cancel();
                }
            });
    final AlertDialog alert = builder.create();
    alert.show();
}




private void turnGPSOff(){
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

if(provider.contains("gps")){ //if gps is enabled
    final Intent poke = new Intent();
    poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
    poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
    poke.setData(Uri.parse("3")); 
    sendBroadcast(poke);
}

}

permission in android 6 down

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

and

permission android 6 up

 if ( ContextCompat.checkSelfPermission(this, 
 android.Manifest.permission.ACCESS_FINE_LOCATION) ==
 PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this,
 android.Manifest.permission.ACCESS_COARSE_LOCATION) == 
PackageManager.PERMISSION_GRANTED) {
        } else {

        Toast.makeText(this, R.string.error_permission_map, Toast.LENGTH_LONG).show();
    }
younes
  • 742
  • 7
  • 8