How to check for the presence of a GPS sensor?

China☆狼群 提交于 2019-12-01 18:58:57

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!

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!