android通知收不到原因NotificationListener

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhuxingchong/article/details/81671909

最近发现launcher收不到应用通知,问题是NotificationListener监听权限关闭了,具体什么原因关闭的现在不知道,网上说应用被kill了再次启动时没有加入该权限,但我验证过kill掉应用不会有这种情况,可能是我在后台通过下面setDefaultNotificationAccess方法重新加入了权限,这些后台加权限的方法不好用,有时成功有时不成功而且不会马上生效,建议主动跳转到设置权限界面。

//主动调到设置界面打开通知监听权限
public void setNotificationAccess(){
    Intent intent = new         
    Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
}

                    
//后台写入
private void setDefaultNotificationAccess() {
        //获取所有通知监听
        final String flat = Settings.Secure.getString(getContentResolver(),
                "enabled_notification_listeners");
        if (flat != null && !"".equals(flat)) {
            //判断是否已经包含了你的,包名+通知监听类
            if (flat.contains("xxxx/xxxx.NotificationListener")) {
                Log.d(TAG, "Nothing to do");
            } else {
                Log.d(TAG, "append xxx");
                StringBuilder flatString = new StringBuilder(flat);
                //追加包名+通知监听类flatString.append(":com.xxx.xxx/com.xxx.xxx.xxx.NotificationListener");
                try {//写入
                    Settings.Secure.putString(getContentResolver(),
                            "enabled_notification_listeners", flatString.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            try {//写入
                Settings.Secure.putString(getContentResolver(),
                        "enabled_notification_listeners",
                        "com.xxx.xxx/com.xxx.xxx.xxx.NotificationListener");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

猜你喜欢

转载自blog.csdn.net/zhuxingchong/article/details/81671909