简体   繁体   English

如何检查用户是否真的在Android中启用了GPS定位?

[英]How to check if the user really enables the GPS location in Android?

My application needs GPS, so when a specific operation is performed I check if the GPS is enabled as following (and as suggested by Marcus in this other question):我的应用需要GPS,所以当执行特定的操作我检查,如果GPS是如下启用(和由Marcus在提出这个其他问题):

if (!locationManager.isProviderEnabled( LocationManager.GPS_PROVIDER )) {
    buildAlertMessageNoGps();
}

rootView = inflater.inflate(R.layout.fragment_alert, container, false);
[...]

The problem is that the user, from the location settings, could not enable the GPS (eg, by clicking on the "back" button and going back to the application).问题是用户无法从位置设置启用 GPS(例如,通过单击“返回”按钮并返回到应用程序)。 In this particular case, the fragment injects the layout for the corresponding process, but the GPS is still disabled.在这种特殊情况下,片段为相应的进程注入了布局,但 GPS 仍处于禁用状态。 How to solve that?如何解决?

I guess this is the method that you are looking for.我想这就是你正在寻找的方法。 You have to check for android version above KitKat.您必须检查 KitKat 以上的 android 版本。

@SuppressLint("InlinedApi") @SuppressWarnings("deprecation")
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 (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);
    }
} 

I solved by replacing startActivity(...) with startActivityForResult(...) in the buildAlertMessageNoGps() method.我通过在buildAlertMessageNoGps()方法中用startActivityForResult(...)替换startActivity(...)来解决。 In doing so, I can check again if the GPS has been enabled in the callback function onActivityResult(...) .这样做时,我可以再次检查是否在回调函数onActivityResult(...)启用了 GPS。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM