Reputation: 1930
I have an Android app that implements a NotificationListenerService. In my notification listener service, I intercept notifications from another app (package) and try to cancel them.
When I call the NotificationManager.cancel() method...nothing happens. No cancel occurs and the notification persists.
The notifications I am intercepting are being sent using Firebase Cloud Messaging...and all notifications arrive with an ID of '0'. I am thinking that maybe the zero ID is a problem, but I do not have control over the ID the notification is being propagated by FCM and not any application code on my part.
I have granted the special notification inspection permission for my app at the OS level (which is why it is able to correctly intercept the notifications).
My notification service listener is as follows...
public class MyNotificationService extends NotificationListenerService {
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
super.onNotificationPosted(sbn);
Log.d("notification-test", sbn.toString());
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.cancel(sbn.getTag() , sbn.getId());
}
}
My AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.my_example_app">
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Androidnativenotificationservicelistener"
tools:targetApi="31">
<service android:name=".MyService"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE"
android:exported="true">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Upvotes: 0
Views: 221
Reputation: 4579
The reason could be that since the NotificationListenerService
observes notifications from all of the installed apps (System & User), your NotificationManager
cannot cancel notifications of other apps.
You could use simply use:
NotificationListenerService#cancelNotification(key: String)
& pass the key via StatusBarNotification#getKey()
.
Example:
public class MyNotificationService extends NotificationListenerService {
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
super.onNotificationPosted(sbn);
cancelNotification(sbn.getKey());
}
}
Upvotes: 1