Reputation: 61
How to open the gps in Android when it is closed to retrieve the current position. I test two method
private void turnGPSOn(){
String provider = Settings.Secure.getString(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"));
sendBroadcast(poke);
}
}
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);
}
}
and this method
enaABLE GPS:
Intent intent=new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
sendBroadcast(intent);
DISABLE GPS:
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", false);
sendBroadcast(intent);
but when opening the gps by one of these methods is execute code recovery position, it displays
Toast.makeText(LbsGeocodingActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
Upvotes: 2
Views: 17012
Reputation: 7041
You can't enable GPS for a user, what you can do is, if GPS s disabled, prompt the user with a message to ask him to enable GPS and send him to the settings to enable it
with this code :
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
This is a more detailed code on how to do it
http://java-blog.kbsbng.com/2012/08/displaying-dialog-in-android-to-prompt.html
To get the location you do this
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
/*try to see if the location stored on android is close enough for you,and avoid rerequesting the location*/
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null
|| location.getTime()
- Calendar.getInstance().getTimeInMillis() > MAX_LAST_LOCATION_TIME)
{
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, TIME_INTERVAL, LOCATION_INTERVAL, yourLocationListener);
}
else
{
//do your handling if the last known location stored on android is enouh for you
}
in yourLocationListener, you implement what to do when you get the location
Upvotes: 11
Reputation: 11900
It's inappropiate to enable GPS from the code. You can't fo that.
There used to be an exploit that allowed the GPS to be turned on by an app with no special permissions. That exploit no longer exists as of 2.3 (in most ROMs).
Upvotes: 0