我正在制作通知拦截器,删除所选应用程序通知。
我在通知侦听器服务中使用了代码段,
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
if(SettingsActivity.SettingsInfo.getInt(sbn.getPackageName(), R.drawable.unblock)==R.drawable.block)
{
if(Build.VERSION.SDK_INT<Build.VERSION_CODES.LOLLIPOP)
cancelNotification(sbn.getPackageName(), sbn.getTag(), sbn.getId());
else
cancelNotification(sbn.getKey());
}
}
但此代码仅清除可取消的通知。但我想删除所选应用程序的所有通知(也包括系统通知)。有没有办法做到这一点?
我也尝试了反射方法。
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancel(sbn.getTag(), sbn.getId());
Class localClass = Class.forName("android.os.ServiceManager");
Method getService = localClass.getMethod("getService", new Class[]{String.class});
if (getService != null) {
Object result = getService.invoke(localClass, new Object[]{Context.NOTIFICATION_SERVICE});
if (result != null) {
IBinder binder = (IBinder) result;
final INotificationManager iNotificationManager = INotificationManager.Stub.asInterface(binder);
int uid = 0;
try {
uid = this.getPackageManager().getApplicationInfo(sbn.getPackageName(), 0).uid;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
iNotificationManager.cancelAllNotifications(sbn.getPackageName(), uid);
}
}
但我正在 Security Exception
as Calling UID gave package owned by other UID
有关详情,我想喜欢
应用 - &gt;应用设置 - &gt;通知 - &gt;全部阻止
提前致谢!!!
答案 0 :(得分:0)
如果您要取消其他应用的通知,则需要使用 NotificationListenerService
它有cancelNotification
方法:
public class NotificationListener extends NotificationListenerService {
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
cancelNotification(sbn.getKey());
}
}
答案 1 :(得分:0)
试试这个并告诉我它是否有效:
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public class NotificationService extends NotificationListenerService {
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
// Store each StatusBarNotification object
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
cancelNotification(sbn.getPackageName(), sbn.getTag(), sbn.getId());
Log.d("Cncel ","Cancel not");
}
else {
cancelNotification(sbn.getKey());
Log.d("key ","Cancel not key");
}
}
@Override
public void onNotificationRemoved(StatusBarNotification sbn) {
// Delete removed StatusBarNotification objects
}
}
答案 2 :(得分:0)
感谢您的回复,从我的研究中我得到了解决方案
使用标记FLAG_NO_CLEAR
清除通知
对于api> 25,您可以延后通知
snoozeNotification(sbn.getKey(), Long.MAX_VALUE);
对于api&gt; 23和&lt; 26,有一种方法可以用于 ovveride组密钥并将它们分组到您的通知中,
statusbarnotification.setOverrideGroupKey("key");
少了api,
您需要 root访问权限或系统权限。然后你可以使用
iNotificationManager.cancelAllNotifications(sbn.getPackageName(), uid);