判断应用是否开启通知栏及跳转到设置页面

今天做项目用到通知,发现在oppo和360手机上,如果不去手动打开状态栏可以获取通知的设置,就算发送通知也看不到消息,但是小米手机就没事,有人说获取手机型号进行适配,但是安卓手机机型太多,那样做是在是头疼,后来有人说可以判断通知栏是否打开,这个方法不错,避免了要去判断所有的机型。

 private boolean isNotificationEnabled(Context context) {
        String CHECK_OP_NO_THROW = "checkOpNoThrow";
        String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";
        AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        ApplicationInfo appInfo = context.getApplicationInfo();
        String pkg = context.getApplicationContext().getPackageName();
        int uid = appInfo.uid;
        Class appOpsClass = null;
     /* Context.APP_OPS_MANAGER */
        try {
            appOpsClass = Class.forName(AppOpsManager.class.getName());
            Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE,
                    String.class);
            Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION);
            int value = (Integer) opPostNotificationValue.get(Integer.class);
            if ((Integer) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) == AppOpsManager.MODE_ALLOWED){
                Toast.makeText(this,"true",Toast.LENGTH_SHORT).show();
            }else {
                Toast.makeText(this,"false",Toast.LENGTH_SHORT).show();
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setMessage("是否跳转到设置页面");
                builder.setTitle("提示");
                builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        goToSet();
                        dialog.dismiss();
                    }
                });
                builder.setNegativeButton("取消",new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.create().show();
            }
            return ((Integer) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) == AppOpsManager.MODE_ALLOWED);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return false;
    }
在这里返回true,表示已经打开通知栏,返回false,弹出dialog选择是否跳转到设置页面,页面跳转方法如下:

 private void goToSet(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BASE) {
            // 进入设置系统应用权限界面
            Intent intent = new Intent(Settings.ACTION_SETTINGS);
            startActivity(intent);
            return;
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {// 运行系统在5.x环境使用
            // 进入设置系统应用权限界面
            Intent intent = new Intent(Settings.ACTION_SETTINGS);
            startActivity(intent);
            return;
        }
    }



要在uni-app中配置点击推送消息后跳转到指定页面,可以通过在`jpushModule.addNotificationListener`中处理点击事件来实现。以下是如何实现这一功能的步骤: 1. **在 `addNotificationListener` 中添加点击事件处理**: 在 `onLaunch` 方法中的 `addNotificationListener` 回调函数中,处理点击事件并导航到指定页面。 2. **使用 `uni.navigateTo` 或 `uni.reLaunch` 进行页面跳转**: 根据需要选择合适的页面跳转方法。 以下是修改后的代码示例: ```javascript export default { data() { return {}; }, onLaunch: function() { this.initApp(); // #ifdef APP-PLUS jpushModule.initJPushService(); jpushModule.setLoggerEnable(true); plus.screen.lockOrientation("portrait-primary"); // 监听 极光推送连接状态 this.getNotificationEnabled(); jpushModule.addConnectEventListener(result => { let connectEnable = result.connectEnable uni.$emit('connectStatusChange', connectEnable) }); jpushModule.addNotificationListener(result => { // 极光推送的消息通知回调 jpushModule.setBadge(0); plus.runtime.setBadgeNumber(0); let notificationEventType = result.notificationEventType; if (notificationEventType === 1) { // 点击通知 const extraData = result.extraData; // 获取额外数据 const page = extraData.page || '/pages/targetPage'; // 默认跳转页面 uni.navigateTo({ // 或者使用 uni.reLaunch url: page }); } }); uni.$on('connectStatusChange', (connectStatus) => { var connectStr = ''; if (connectStatus == true) { connectStr = '已连接'; // this.getRegistrationID() } else { connectStr = '未连接'; } console.log('监听到了连接状态变化 --- ', connectStr); this.connectStatus = connectStr; }); jpushModule.isPushStopped(res => { // code 0已停止推送 1未停止推送 const { code } = res; console.log(res, '安卓连接状态'); }); // #endif }, created() { this.getRegistrationID(); }, methods: { // 初始化应用 initApp() { // 初始化应用配置 this.initConfig(); // 检查用户登录状态 //#ifdef H5 this.checkLogin(); //#endif }, initConfig() { this.globalData.config = config; }, checkLogin() { if (!getToken()) { this.$tab.reLaunch('/pages/login'); } }, getRegistrationID() { // 获取registerID jpushModule.getRegistrationID(result => { let registerID = result.registerID; console.log("@@@@@@@registerID = " + registerID); uni.setStorageSync("registerID", registerID); }); }, getNotificationEnabled() { if (uni.getSystemInfoSync().platform == "ios") { jpushModule.requestNotificationAuthorization((result) => { let status = result.status; if (status < 2) { this.noticMsgTool(); } }); } else { jpushModule.isNotificationEnabled((result) => { // 判断android是否打开权限 if (result.code == 0) { // 如果为0则表示 未打开通知权限 this.noticMsgTool(); } }); } }, noticMsgTool() { if (uni.getSystemInfoSync().platform == "ios") { // 苹果打开对应的通知栏 uni.showModal({ title: '通知权限开启提醒', content: '您还没有开启通知权限,无法接受到消息通知,请前往设置!', showCancel: false, 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"); uni.showModal({ title: '通知权限开启提醒', content: '您还没有开启通知权限,无法接受到消息通知,请前往设置!', showCancel: false, confirmText: '去设置', success: function(res) { if (res.confirm) { var Intent = plus.android.importClass('android.content.Intent'); var Build = plus.android.importClass("android.os.Build"); // android 8.0引导 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)其他--跳转到该应用管理的详情页 intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); var uri = Uri.fromParts("package", mainActivity.getPackageName(), null); intent.setData(uri); } // 跳转到该应用的系统通知设置页 main.startActivity(intent); } } }); } }, } } ``` ### 关键点解释: 1. **`addNotificationListener` 回调**:在 `addNotificationListener` 回调中,检查 `notificationEventType` 是否为 `1`(表示点击通知)。 2. **获取额外数据**:通过 `result.extraData` 获取推送消息中的额外数据,这些数据可以包含目标页面的路径。 3. **页面跳转**:使用 `uni.navigateTo` 或 `uni.reLaunch` 方法进行页面跳转。`uni.navigateTo` 用于在当前页面栈基础上增加一个新页面,`uni.reLaunch` 用于关闭所有页面,打开到应用内的某个页面。 这样,当用户点击推送消息时,应用跳转到指定的页面
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值