如何在API 18及更低版本上检查位置是否已开启且具有高优先级

Jan*_*Jan 14 android

试过这个:

String locationProviders = Settings.Secure.getString(getActivity().getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
Log.d(TAG_MAP, locationProviders);
Run Code Online (Sandbox Code Playgroud)

输出是:gps,网络

API 18及以下的手机是否具有HIGH_ACCURACY优先级?

Dan*_*ent 22

我假设您想知道如何使用Settings.Secure.LOCATION_PROVIDERS_ALLOWEDAPI(在API级别19中进行描述)与使用不同Settings.Secure.LOCATION_MODE,后者在API级别19中引入.

有了Settings.Secure.LOCATION_MODE,你有这些价值(你可能已经知道了):

LOCATION_MODE_HIGH_ACCURACY,LOCATION_MODE_SENSORS_ONLY,LOCATION_MODE_BATTERY_SAVING或LOCATION_MODE_OFF

您可以通过以下Settings.Secure.LOCATION_PROVIDERS_ALLOWED方式映射这些值:

LOCATION_MODE_HIGH_ACCURACY:"gps,网络"

LOCATION_MODE_SENSORS_ONLY:"gps"

LOCATION_MODE_BATTERY_SAVING:"网络"

LOCATION_MODE_OFF:""

请注意,在代码中,这是最好的参考常数LocationManager.GPS_PROVIDERLocationManager.NETWORK_PROVIDER,而不是仅仅"GPS"和"网络".

使用此答案作为参考,您可以执行以下操作:

public static int getLocationMode(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();
        }


    } else {
        locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

        if (TextUtils.isEmpty(locationProviders)) {
          locationMode = Settings.Secure.LOCATION_MODE_OFF;
        }
        else if (locationProviders.contains(LocationManager.GPS_PROVIDER) && locationProviders.contains(LocationManager.NETWORK_PROVIDER)) {
          locationMode = Settings.Secure.LOCATION_MODE_HIGH_ACCURACY;
        }
        else if (locationProviders.contains(LocationManager.GPS_PROVIDER)) {
           locationMode = Settings.Secure.LOCATION_MODE_SENSORS_ONLY;
        }
        else if (locationProviders.contains(LocationManager.NETWORK_PROVIDER)) {
           locationMode = Settings.Secure.LOCATION_MODE_BATTERY_SAVING;
        }

    }

    return locationMode;
} 
Run Code Online (Sandbox Code Playgroud)