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.
1 Answer
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);
}
}
-
2hi 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..– SandeepJun 2, 2013 at 10:00
-
4try 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
-
3For 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
-
4I 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