I used the below code which was there in Stack Overflow to check whether GPS is enabled or disabled on a device
public static boolean isLocationEnabled(Context context) {
int locationMode = 0;
String locationProviders;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
try {
locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
return locationMode != Settings.Secure.LOCATION_MODE_OFF;
} else {
locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
return !TextUtils.isEmpty(locationProviders);
}
}
It works fine on my device (Huawei G610) and I have no issues with it. Then I gave the application to a friend who's using a Samsung Galaxy Note, he tells that it doesn't notify whether GPS service is not enabled.
This function is used to trigger an alert dialog if GPS is not enabled to ask user to enable it.
I have no idea why it isn't working on his device, your help is highly appreciated. I am asking about the reason behind it not working on some devices and working on some.
Thanks.
You can check if location is enabled or not using the following code. I will work in all the devices
LocationManager location_manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
LocationListener listner = new MyLocationListener();
boolean networkLocationEnabled = location_manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
boolean gpsLocationEnabled = location_manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (networkLocationEnabled || gpsLocationEnabled) {
if (location_manager.getAllProviders().contains(LocationManager.NETWORK_PROVIDER) && networkLocationEnabled) {
location_manager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 2000, 2000, listner);
location_manager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
} else if (location_manager.getAllProviders().contains(LocationManager.GPS_PROVIDER) && gpsLocationEnabled) {
location_manager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 2000, 2000, listner);
location_manager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);