如何检查我是否在Android 4.4及以上版本中以编程方式打开gps? [重复]

问题描述 投票:3回答:2

这个问题在这里已有答案:

我曾尝试在线搜索答案,但它们似乎只适用于Android 4.0及更低版本

java android gps android-4.4-kitkat
2个回答
2
投票
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 false;
        }

        return locationMode != Settings.Secure.LOCATION_MODE_OFF;

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


} 

1
投票

你可以使用LocationManager

此类提供对系统位置服务的访问。这些服务允许应用程序获取设备的地理位置的定期更新,或者在设备进入给定地理位置附近时触发应用程序指定的Intent。

这是您正在寻找的代码片段

LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))

这已经过Android 4.4及以上版本的测试。但不适用于8.0。

© www.soinside.com 2019 - 2024. All rights reserved.