这是我的服务:
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/