判断定位服务是否开启(手机上位置信息按钮开关)

来源:互联网 发布:js获取另一个页面的id 编辑:程序博客网 时间:2024/05/06 02:50

今天遇到vivoX6手机 定位服务在没有开启的情况下返回的也是开启的,打印log竟然是true;
反复思考查找后,最后发现判断代码是有问题的。


之前一直用判断GPS和网络情况,来判断定位服务:

    /**     * 判断GPS是否开启,GPS或者AGPS开启一个就认为是开启的     *     * @param     * @return true 表示开启     */    public static final boolean isOPen(final Context context) {        LocationManager locationManager                = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);        // 通过GPS卫星定位,定位级别可以精确到街(通过24颗卫星定位,在室外和空旷的地方定位准确、速度快)        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);        // 通过WLAN或移动网络(3G/2G)确定的位置(也称作AGPS,辅助GPS定位。主要用于在室内或遮盖物(建筑群或茂密的深林等)密集的地方定位)        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);        if (gps || network) {            return true;        }        return false;    }

发现这种方式在一部分手机上是存在问题的,不是解决问题的关键;


经过同事分析他之前写的代码,测试发现可行

  /**     * 判断定位服务是否开启     *     * @param     * @return true 表示开启     */    public boolean isLocationEnabled() {        int locationMode = 0;        String locationProviders;        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {            try {                locationMode = Settings.Secure.getInt(getContentResolver(), Settings.Secure.LOCATION_MODE);            } catch (Settings.SettingNotFoundException e) {                e.printStackTrace();                return false;            }            return locationMode != Settings.Secure.LOCATION_MODE_OFF;        } else {            locationProviders = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);            return !TextUtils.isEmpty(locationProviders);        }    }

这种方式才是解决 判断定位服务按钮是否开启的源码,经测试 可行,如后续遇到问题 会继续更新。。。

原创粉丝点击