30

I am creating an anti-theft application and, locating my phone through sms and it works perfectly until 2.3. But in 4.0 I can't turn on or off gps programmatically is there any other possible way to switch on gps through code.

3

1 Answer 1

40

Try using this code. It worked for me on all the versions.

public void turnGPSOn()
{
     Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
     intent.putExtra("enabled", true);
     this.ctx.sendBroadcast(intent);

    String provider = Settings.Secure.getString(ctx.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
    if(!provider.contains("gps")){ //if gps is disabled
        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);


    }
}
// automatic turn off the 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);
    }
}
14
  • 2
    hi it is not working in samsung galaxy y. it put gps receiver is on always on mode, after getting fix it should be on sleep mode..
    – Sandeep
    Jun 2, 2013 at 10:00
  • 4
    try this code to turn off gps Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE"); intent.putExtra("enabled", false); sendBroadcast(intent); Jun 3, 2013 at 7:21
  • 3
    For those who are facing problem with "ctx". ctx is nothing but instance of the activity. If you declare these functions in your activity then use "className.this" instead of ctx. Nov 29, 2013 at 6:41
  • 4
    I am getting "java.lang.SecurityException: Permission Denial: not allowed to send broadcast android.location.GPS_ENABLED_CHANGE". App is crashing Jun 5, 2015 at 6:15
  • 10
    this does not work anymore since Android 4.4
    – Leo
    Mar 30, 2016 at 20:43

Not the answer you're looking for? Browse other questions tagged or ask your own question.