On an Android Cupcake (1.5) enabled device, how do I check and activate the GPS?
Yes you can check below is the code:
public boolean isGPSEnabled (Context mContext){
LocationManager locationManager = (LocationManager)
mContext.getSystemService(Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
In your LocationListener
, implement onProviderEnabled
and onProviderDisabled
event handlers. When you call requestLocationUpdates(...)
, if GPS is disabled on the phone, onProviderDisabled
will be called; if user enables GPS, onProviderEnabled
will be called.
yes GPS settings cannot be changed programatically any more as they are privacy settings and we have to check if they are switched on or not from the program and handle it if they are not switched on. you can notify the user that GPS is turned off and use something like this to show the settings screen to the user if you want.
Check if location providers are available
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(provider != null){
Log.v(TAG, " Location providers: "+provider);
//Start searching for location and update the location text when update available
startFetchingLocation();
}else{
// Notify users and show settings if they want to enable GPS
}
If the user want to enable GPS you may show the settings screen in this way.
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(intent, REQUEST_CODE);
And in your onActivityResult you can see if the user has enabled it or not
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == REQUEST_CODE && resultCode == 0){
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(provider != null){
Log.v(TAG, " Location providers: "+provider);
//Start searching for location and update the location text when update available.
// Do whatever you want
startFetchingLocation();
}else{
//Users did not switch on the GPS
}
}
}
Thats one way to do it and i hope it helps. Let me know if I am doing anything wrong.
This method will use the LocationManager service.
Source Link
//Check GPS Status true/false
public static boolean checkGPSStatus(Context context){
LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE );
boolean statusOfGPS = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
return statusOfGPS;
};