所有通知(甚至是其他应用程序通知)都可以通过监听NotificationListenerService 实现中提到的“NotificationListenerService”来删除
在服务中你必须调用cancelAllNotifications()
。
必须通过“应用程序和通知”->“特殊应用访问”->“通知访问”为您的应用程序启用该服务。
添加到清单:
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:label="Test App" android:name="com.test.NotificationListenerEx" android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
然后在代码中;
public class NotificationListenerEx extends NotificationListenerService {
public BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
NotificationListenerEx.this.cancelAllNotifications();
}
};
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
super.onNotificationPosted(sbn);
}
@Override
public void onNotificationRemoved(StatusBarNotification sbn) {
super.onNotificationRemoved(sbn);
}
@Override
public IBinder onBind(Intent intent) {
return super.onBind(intent);
}
@Override
public void onDestroy() {
unregisterReceiver(broadcastReceiver);
super.onDestroy();
}
@Override
public void onCreate() {
super.onCreate();
registerReceiver(broadcastReceiver, new IntentFilter("com.test.app"));
}
之后使用广播接收器触发清除所有。
按照上面的代码触发广播使用;
getContext().sendBroadcast(new Intent("com.test.app"));