android - 无法使用 NotificationListenerService 取消通知

标签 android android-service android-notifications

这是我的服务:

public class Listener extends NotificationListenerService {
    Context context;

    @Override

    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
    }

    @Override

    public void onNotificationPosted(StatusBarNotification sbn) {
        String pack = sbn.getPackageName();
        String ticker = sbn.getNotification().tickerText.toString();
        Bundle extras = sbn.getNotification().extras;
        String title = extras.getString("android.title");
        String text = extras.getCharSequence("android.text").toString();

        Log.i("Msg",pack);
        Log.i("Msg",ticker);
        Log.i("Msg",title);
        Log.i("Msg",text);

        Intent msgrcv = new Intent("Msg");
        msgrcv.putExtra("package", pack);
        msgrcv.putExtra("ticker", ticker);
        msgrcv.putExtra("title", title);
        msgrcv.putExtra("text", text);
            LocalBroadcastManager.getInstance(context).sendBroadcast(msgrcv);
        Toast.makeText(context, "GOT SOMETHING", Toast.LENGTH_LONG).show();

 //final String T=  sbn.getKey();

        Listener.this.cancelAllNotifications();
    }

    @Override

    public void onNotificationRemoved(StatusBarNotification sbn) {
        Log.i("Msg","Notification Removed");
    }
}

为了测试,我想在它们到达时立即关闭来自任何应用程序的所有通知。我在 onNotificationPosted 中调用了 Listener.this.cancelAllNotifications();,但它不起作用。

我做错了什么?我正在 Android 版本 5.0.2 上对此进行测试。

附言

我已经添加了权限和 intent 过滤器,正如 android 提到的那样。

<service android:name=".NotificationListener"
          android:label="@string/service_name"
          android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
     <intent-filter>
         <action android:name="android.service.notification.NotificationListenerService" />
     </intent-filter>
 </service>

最佳答案

确保实现您的 NotificationListenerService 的应用的“通知访问”处于 Activity 状态(选中)。

可以在“设置”菜单中验证。它位于任一地址,具体取决于 Android 版本。对于 Android 5.0,它应该位于: 设置 -> 声音和通知 -> 通知访问

否则,您可以在以下位置找到: 设置 -> 安全 -> 通知访问

尝试为您的应用启用它,然后尝试清除通知。

关于android - 无法使用 NotificationListenerService 取消通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29803218/

相关文章:

Android Studio EditText更新

android - 如何将高度设置为底部导航

Android:如何避免 Activity 被系统杀死,ActivityManager:处理我的包名称(pid 935)已死亡

Android 多行通知,如 Gmail 应用程序

Android - 显示动画状态栏图标

android:如何通过编码而不是通过 XML 将 TextView 设置为粗体

android - 为什么BroadcastReceiver没有在后台运行?

android - 创建一项服务来完成 Activity 的所有艰苦工作是个好主意吗?

java - 通知监听器服务并不总是工作

android - 通知不打开 fragment ?