uniapp obtains mobile phone positioning permission and prohibits jumping to the settings page after rejection

Problem: Obtaining the mobile phone positioning permission, after the user clicks to reject, and then clicks the positioning button again, the mobile phone does not respond. Here, after the Android system rejects it twice, it defaults to disabling the inquiry pop-up window from popping up, so there will definitely be no response when clicking the position again.

1. Solution: The first thought is to check whether the GPS function (Android) is turned on. If it is turned on, it will jump directly to the map positioning page. If it is turned off, it will jump to the system settings;

The following are all Android examples:

Original code:

import { checkOpenGPSServiceByAndroid } from "@/utils/device";
/*.
.
.
*/
/*
定位按钮触发事件
*/
onGPSAddress() {
      checkOpenGPSServiceByAndroid()
      // 获取当前位置
      uni.getLocation({
        type: "gcj02", //返回可以用于uni.openLocation的经纬度
        success: res => {
          let latitude = res.latitude;
          let longitude = res.longitude;
          uni.chooseLocation({
            latitude,
            longitude,
            success: data => {
              //此处仅返回详细地址和经纬度,所以要进行经纬度解析
              this.getCity(data.latitude, data.longitude);
            },
            fail: fail => {
              checkOpenGPSServiceByAndroid();
            }
          });
        }
      });
    },
    // 解析经纬度
    getCity(latitude, longitude) {
      let location = `${longitude},${latitude}`;
      var myAmapFun = new amapFile.AMapWX({
        key: amapKey,
        batch: true
      });
      myAmapFun.getRegeo({
        //如果经纬度有问题会导致不进入回调方法,从而报错
        location: location,
        success: e => {
          //成功回调
          console.log(e);
          let addressComponent = e[0].regeocodeData.addressComponent;
          let formatted_address = e[0].regeocodeData.formatted_address;
          this.detail = formatted_address;
          this.city = addressComponent.city;
          this.province = addressComponent.province;
          this.provinceCity = addressComponent.province + addressComponent.city;
          this.district = addressComponent.district;
          this.districtId = addressComponent.adcode;
          this.location = e[0].location;
          this.longitude = e[0].longitude;
        },
        fail: function (info) {
          //失败回调
          console.log(info);
        }
      });
    },

device.js file:

let system = uni.getSystemInfoSync(); // 获取系统信息
/**检查是否打开GPS功能(android)**/
export const checkOpenGPSServiceByAndroid = () => {
        if (system.platform === 'android') { // 判断平台
            var context = plus.android.importClass("android.content.Context");
            var locationManager = plus.android.importClass("android.location.LocationManager");
            var main = plus.android.runtimeMainActivity();
            var mainSvr = main.getSystemService(context.LOCATION_SERVICE);
            if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
                uni.showModal({
                    title: '提示',
                    content: '请打开定位服务功能',
                    success(res) {
                        if (res.confirm) {
                            if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
                                var Intent = plus.android.importClass('android.content.Intent');
                                var Settings = plus.android.importClass('android.provider.Settings');
                                var intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                main.startActivity(intent); // 打开系统设置GPS服务页面
                            } else {
                                console.log('GPS功能已开启');
                            }
                        }
                    }
                });
                return
            }
        }
    }

/* 该问题用不到下面的方法,请忽略 */

/**
 * 检查通知是否开启
 */
export const noticMsgTool = () => {
    //如果没有打开 则可以 去 请求打开
    if (system.platform == "ios") {
        //苹果打开对应的通知栏
        uni.showModal({
            title: "通知权限开启提醒",
            content: "您还没有开启通知权限,无法接受到消息通知,请前往设置!",
            confirmText: "去设置",
            success: function(res) {
                if (res.confirm) {
                    var app = plus.ios.invoke("UIApplication", "sharedApplication");
                    var setting = plus.ios.invoke("NSURL", "URLWithString:", "app-settings:");
                    plus.ios.invoke(app, "openURL:", setting);
                    plus.ios.deleteObject(setting);
                    plus.ios.deleteObject(app);
                }
            }
        });
    } else {
        //android打开对应的通知栏
        var main = plus.android.runtimeMainActivity();
        var pkName = main.getPackageName();
        var uid = main.getApplicationInfo().plusGetAttribute("uid");
        var Intent = plus.android.importClass('android.content.Intent');
        var Build = plus.android.importClass("android.os.Build");
        uni.showModal({
            title: "通知权限开启提醒",
            content: "您还没有开启通知权限,无法接受到消息通知,请前往设置!",
            confirmText: "去设置",
            success: function(res) {
                if (res.confirm) {
                    if (Build.VERSION.SDK_INT >= 26) {
                        var intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS');
                        intent.putExtra('android.provider.extra.APP_PACKAGE', pkName);
                    } else if (Build.VERSION.SDK_INT >= 21) { //android 5.0-7.0  
                        var intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS');
                        intent.putExtra("app_package", pkName);
                        intent.putExtra("app_uid", uid);
                    } else { //(<21)其他--跳转到该应用管理的详情页
                        var Settings = plus.android.importClass("android.provider.Settings");
                        var Uri = plus.android.importClass("android.net.Uri");
                        var intent = new Intent();
                        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        var uri = Uri.fromParts("package", main.getPackageName(), null);
                        intent.setData(uri);
                    }
                    // 跳转到该应用的系统通知设置页  
                    main.startActivity(intent);

                }
            }
        });
    }
}

After Du Niang ' detected whether Android's GPS function is turned on ', the codes were all the above 5+ methods. When testing the PDA (Android 9.0 version), the above code detection was always turned on. The above code detection is always disabled on Transsion mobile phones (Android 10 version). If you use the above code to open the settings page, the information location authorization pop-up window will not pop up.

2. Solution idea: Detect user operation pop-up window rejection, prohibition, and allow events. If the required permission is denied, open the APP settings interface, and you can open the corresponding permissions in the APP settings interface;

device.js file code adjustment:

let system = uni.getSystemInfoSync(); // 获取系统信息
/**检查是否打开GPS功能(android)**/
export const checkOpenGPSServiceByAndroid = () => {
        if (system.platform === 'android') { // 判断平台
          
            openGps();
        }
    }
    /**
     * 定位权限及弹出权限弹框 监听用户点击按钮
     * **/
export const openGps = () => {
    plus.android.requestPermissions(
        ['android.permission.ACCESS_FINE_LOCATION'],
        function(resultObj) {
            console.log('resultObj---', resultObj);
            var result = 0;
            for (var i = 0; i < resultObj.granted.length; i++) {
                var grantedPermission = resultObj.granted[i];
                // console.log(6, '已获取的权限:' + grantedPermission);
                result = 1
            }
            for (var i = 0; i < resultObj.deniedPresent.length; i++) {
                var deniedPresentPermission = resultObj.deniedPresent[i];
                // console.log(5, '拒绝本次申请的权限:' + deniedPresentPermission);
      
                result = 0
            }
            for (var i = 0; i < resultObj.deniedAlways.length; i++) {
                var deniedAlwaysPermission = resultObj.deniedAlways[i];
                // console.log(4, '永久拒绝申请的权限:' + deniedAlwaysPermission);
            
                result = -1
            }
            // 若所需权限被拒绝,则打开APP设置界面,可以在APP设置界面打开相应权限
            if (result != 1) {
                //如果用户第一次拒绝后,跳转到**应用**的权限页面
                 var Intent = plus.android.importClass("android.content.Intent");
                 var Settings = plus.android.importClass("android.provider.Settings");
                 var Uri = plus.android.importClass("android.net.Uri");
                 var mainActivity = plus.android.runtimeMainActivity();
                 var intent = new Intent();
                 intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                 var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
                 intent.setData(uri);
                 mainActivity.startActivity(intent);
            }
        },
        function(error) {
            console.log('申请权限错误:' + error.code + " = " + error.message);
            resolve({
                code: error.code,
                message: error.message
            });
        }
    );
}

Every time the user refuses, it will jump to setting permissions, which is unreasonable.

3. Solution: After the user refuses twice, the user clicks the location again and is prompted to set permissions. And jump to system settings;

device.js file code adjustment:

let system = uni.getSystemInfoSync(); // 获取系统信息
/**检查是否打开GPS功能(android)**/
export const checkOpenGPSServiceByAndroid = () => {
        if (system.platform === 'android') { // 判断平台
            
            openGps();
        }
    }
    /**
     * 定位权限及弹出权限弹框 监听用户点击按钮
     * **/
let num = 0;
export const openGps = () => {
    plus.android.requestPermissions(
        ['android.permission.ACCESS_FINE_LOCATION'],
        function(resultObj) {
            console.log('resultObj---', resultObj);
            var result = 0;
            for (var i = 0; i < resultObj.granted.length; i++) {
                var grantedPermission = resultObj.granted[i];
                // console.log(6, '已获取的权限:' + grantedPermission);
                result = 1
            }
            for (var i = 0; i < resultObj.deniedPresent.length; i++) {
                var deniedPresentPermission = resultObj.deniedPresent[i];
                // console.log(5, '拒绝本次申请的权限:' + deniedPresentPermission);
                num += 1
                result = 0
            }
            for (var i = 0; i < resultObj.deniedAlways.length; i++) {
                var deniedAlwaysPermission = resultObj.deniedAlways[i];
                // console.log(4, '永久拒绝申请的权限:' + deniedAlwaysPermission);
                num += 1
                result = -1
            }
            // 若所需权限被拒绝,则打开APP设置界面,可以在APP设置界面打开相应权限
            if (result != 1) {
                //如果用户第2次拒绝后,跳转到**应用**的权限页面
                if (num > 2) {
                    uni.showToast({
                        title: "请到系统设置打开定位服务功能!",
                        icon: "none",
                        duration: 1500
                    })
                    setTimeout(() => {
                        var Intent = plus.android.importClass("android.content.Intent");
                        var Settings = plus.android.importClass("android.provider.Settings");
                        var Uri = plus.android.importClass("android.net.Uri");
                        var mainActivity = plus.android.runtimeMainActivity();
                        var intent = new Intent();
                        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
                        intent.setData(uri);
                        mainActivity.startActivity(intent);
                    }, 2000)
                }
                
          
            }
        },
        function(error) {
            console.log('申请权限错误:' + error.code + " = " + error.message);
            resolve({
                code: error.code,
                message: error.message
            });
        }
    );
}

Android test works;

If there is anything wrong or unclear, please feel free to discuss and correct me~

Guess you like

Origin blog.csdn.net/weixin_42220533/article/details/128967939