开发者

How to check for the presence of a GPS sensor?

I'm writing a method that will return true if there's a GPS sensor present and enabled, but returns false if it's absent or switched off. It's proving hard because...

hasSystemFeature("FEATURE_LOCATION_GPS")  // on PackageManager

Returns false, whether the device has a GPS or not. So even on a device that has one, and it's switched on, it still returns false. Seems completely wrong to me, but I can't see why.

isProviderEnabled("gps")   // on LocationManager

Returns true, even on a device I have here that has no GPS hardware at all. That also seems completely counter-intuitive.

I accept these resu开发者_如何学编程lts could be because I'm missing something, the SDK isn't intuitive, or perhaps even that the devices I'm testing with are behaving strangely.

What am I missing?


This should work. Is there any error messages in logcat when you make this call?

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


In case when device does not have GPS hardware the following is true:

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

Where

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

In my case the *hasSystemFeature(PackageManager.FEATURE_LOCATION_GPS)* returns true even if device does not have GPS. So it's not reliable.


Your hasSystemFeature() probably always returns false because FEATURE_LOCATION_GPS is a reference to a constant, and not a string literal. I believe the current string literal it points to is actually "android.hardware.location.gps".

I believe what you are looking for is something like this:

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 the extra about the AlertDialog to point out that you can take the user to the Location settings page directly to have them enable GPS using the Settings.ACTION_LOCATION_SOURCE_SETTINGS Intent action.

Hope that helps!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜