Android | Check & Enable Location Service

get-location In a previous post Android | Get Last (Current) Location , we have seen how to get device current location using fused location provider APIs. But, what if the location service is not enabled?! Here we will see how to check if the location service is enabled or not and how to take the user directly to the screen where he can enable it.

( 1 ) Check if the Location Service is Enabled

  • This function checks if the location service is enabled or not.
  • It returns true if yes and false otherwise.
Context context;
public boolean isLocationServiceEnabled(){
    LocationManager locationManager = null;
     boolean gps_enabled= false,network_enabled = false;
     
     if(locationManager ==null)
         locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
     try{
         gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
     }catch(Exception ex){
         //do nothing...
     }
     
     try{
        network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
     }catch(Exception ex){
         //do nothing...
     }
     
     return gps_enabled || network_enabled;

}

( 2 ) Enable Location Service

  • If the service is not enabled you may like to take the user directly to the screen where he can enable it.
  • You can achieve this by starting an external activity as following:
 Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
 context.startActivity(myIntent);