How to check if gps i turned on or not programmatically in android version 4.4 and above? [duplicate]

荒凉一梦 提交于 2019-12-06 07:09:38

问题


I have tried searching for answers online but they seemed to work only for android versions 4.0 and below


回答1:


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);
    }


} 



回答2:


You can use LocationManager

This class provides access to the system location services. These services allow applications to obtain periodic updates of the device's geographical location, or to fire an application-specified Intent when the device enters the proximity of a given geographical location.

Here is a code snippet for what you are looking for

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

This has been tested from Android 4.4 and above versions.But Doesn't work for 8.0.



来源:https://stackoverflow.com/questions/44024009/how-to-check-if-gps-i-turned-on-or-not-programmatically-in-android-version-4-4-a

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