Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I enable disable GPS programmatically in Android? [duplicate]

Tags:

android

gps

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.

like image 435
Gopi.cs Avatar asked Mar 15 '13 06:03

Gopi.cs


People also ask

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

Programmatically we can turn on GPS in two ways. First, redirect the user to location settings of a device (by code) or another way is to ask to turn on GPS by GPS dialog using LocationSettingsRequest and SettingsClient.

How do I enable GPS permission on Android?

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.

How do I open location settings in android programmatically?

Get current location settingsTask<LocationSettingsResponse> task = client. checkLocationSettings(builder. build()); When the Task completes, your app can check the location settings by looking at the status code from the LocationSettingsResponse object.


1 Answers

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);     } } 
like image 95
Sagar Patil Avatar answered Sep 21 '22 09:09

Sagar Patil