How to check the availability of a GPS sensor?

I am writing a method that will return true if a GPS sensor is present and turned on, but returns false if it is missing or turned off. This is hard to prove because ...

hasSystemFeature("FEATURE_LOCATION_GPS")  // on PackageManager

Returns false whether the device has a GPS or not. Thus, even on a device that has one, and it turns on, it still returns false. It seems completely wrong to me, but I donโ€™t understand why.

isProviderEnabled("gps")   // on LocationManager

It returns true, even on the device that I have, where there is no GPS equipment at all. It also seems completely contradictory.

I accept that these results may be due to the fact that I missed something, the SDK is not intuitive, or maybe even the devices with which I am testing behave strangely.

What am I missing?

+5
3

. logcat ?

PackageManager pm = getPackageManager();
boolean hasGps = pm.hasSystemFeature(PackageManager.FEATURE_LOCATION_GPS);
+13

GPS, :

locationManager.getProvider(LocationManager.GPS_PROVIDER) == null;

LocationManager locationManager = (LocationManager) AppCore.context().getSystemService(Context.LOCATION_SERVICE);

* hasSystemFeature (PackageManager.FEATURE_LOCATION_GPS) * true, GPS. .

+2

hasSystemFeature(), , false, FEATURE_LOCATION_GPS , . , , , "android.hardware.location.gps".

, - :

LocationManager manager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
if(!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
    //Ask the user to enable GPS
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Location Manager");
    builder.setMessage("Would you like to enable GPS?");
    builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            //Launch settings, allowing user to make a change
            Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(i);
        }
    });
    builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            //No location service, no Activity
            finish();
        }
    });
    builder.create().show();
}

I added additional information about AlertDialogto indicate that you can immediately go to the location settings page to enable GPS using the Settings.ACTION_LOCATION_SOURCE_SETTINGSIntent action .

Hope this helps!

+1
source

All Articles