1

I need to disable GPS programmatically after some event, i am using following method, but i am not able to do it...

 private void turnGPSOff(){
        String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        if(provider.contains("gps")){
            final Intent intent = new Intent();
            intent.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
            intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
            intent.setData(Uri.parse("3"));
            sendBroadcast(intent);
            Toast.makeText(getBaseContext(), "GPS Turned off..!", Toast.LENGTH_LONG).show();
        }
    }
Anand K
  • 233
  • 1
  • 6
  • 21
  • Go to my answer: [http://stackoverflow.com/questions/20740365/programmatically-turn-on-gps-in-android/20740483#20740483](http://stackoverflow.com/questions/20740365/programmatically-turn-on-gps-in-android/20740483#20740483) – M D Jan 27 '14 at 13:28
  • @MD ya, but always keeping GPS on consumes battery power, so i wanted to do this.. – Anand K Jan 27 '14 at 13:32

2 Answers2

1

Try this for turning off GPS

public void turnGPSOff()
{
    String provider = Settings.Secure.getString(ctx.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")); 
        this.ctx.sendBroadcast(poke);
    }
}

But you can do it only on 2.3 our less version. you can not do it on 4.x because it is not possible, for obvious privacy reasons. While there were some hacks, like the one in your question, that used to work, those security flaws have since been fixed.

Umer
  • 1,566
  • 2
  • 20
  • 31
  • so how could we achieve it in android 4.x ? – gumuruh Jul 12 '14 at 04:16
  • You can't but you can gave user option for turning on/off GPS ... Intent gpsOptionsIntent = new Intent( android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(gpsOptionsIntent); – Umer Jul 12 '14 at 08:16
  • 1
    Could you give any reference where I can read about this fix in 4.X versions please? – Shad Aug 13 '14 at 14:55
0
LocationManager L = (LocationManager) getSystemService(LOCATION_SERVICE); 

if (!L.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
     Intent I = new Intent( 
                android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);  
        startActivity(I);  
}
Naveed Ahmad
  • 6,627
  • 2
  • 58
  • 83