How to know in android if location is turned off by user [duplicate]

半城伤御伤魂 提交于 2019-12-11 16:52:45

问题


How can I identify that if the location turned off by the user in android? I also want to show a dialog to go to settings.


回答1:


public static boolean canGetLocation() {
    return isLocationEnabled(App.appInstance); // application context
}

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 (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }
        return locationMode != Settings.Secure.LOCATION_MODE_OFF;
    } else {
        locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
        return !TextUtils.isEmpty(locationProviders);
    }
}

This is a quick tool to check if device location is enabled or not, Hope this helps.

This will return a boolean indicating enabled or not.

And you can navigate not location settings by using the following intent from the alert dialog click listener,

startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));



回答2:


You can trigger a broadcast receiver to know the gps is turned on/ off.

answer is here : How to trigger broadcast receiver when gps is turn on/off?

to check if gps is on or off : How to check if GPS is Disabled Android



来源:https://stackoverflow.com/questions/48017537/how-to-know-in-android-if-location-is-turned-off-by-user

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