阻止或删除所有传入通知的其他应用程序在android工作室编程



大家好,希望大家都过得好。我想问如何删除或阻止任何传入通知(来自其他应用程序,如什么应用程序,instagram等)在android编程。

下面是我用来阻止通知的代码片段,但它不起作用。

class BlockNotification : NotificationListenerService() {
override fun onBind(intent: Intent): IBinder? {
return super.onBind(intent)
}
@RequiresApi(Build.VERSION_CODES.Q)
override fun onNotificationPosted(sbn: StatusBarNotification) {

Log.d("Msg", "Notification arrived ${sbn.packageName},${sbn.id},${sbn.key},${sbn.uid}")

if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
cancelNotification(sbn.packageName, sbn.tag, sbn.id)
} else {
cancelNotification(sbn.key)
}
}
@RequiresApi(Build.VERSION_CODES.Q)
override fun onNotificationRemoved(sbn: StatusBarNotification) {
// Implement what you want here
Log.d("Msg", "Notification Removed")
clearNotofication(sbn.uid)
cancelNotification(sbn.key)
}
private fun clearNotofication(notificationId: Int) {
val ns = NOTIFICATION_SERVICE
val nMgr = this.getSystemService(ns) as NotificationManager
nMgr.cancel(notificationId)
}
}

还在manifest文件中声明了服务。

<service
android:name=".utils.BlockNotification"
android:exported="true"
android:label="@string/app_name"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
<meta-data
android:name="android.service.notification.default_filter_types"
android:value="conversations|alerting" />
<meta-data
android:name="android.service.notification.disabled_filter_types"
android:value="ongoing|silent" />
</service>
如果有人有任何想法,请让我知道!!
NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(NOTIFICATION_ID);

您可以通过在类的参数

中签名context来获取上下文。那么你可以清除通知栏中的所有通知

notificationManager.cancelAll();

或者在你的情况下,通过使用它的id只删除一个通知,就像你在上一个函数

中所做的那样
notificationManager.cancle(notification_id);

或者与标签一起使用我认为这不是你想要的而是让你知道它的存在

notificationManager.cancle(your_tag, notification_id);

你查看文档以获取解释

相关内容

最新更新