可以通过侦听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"));