问题
In my Android app there is a long-running service (export data) which shows progress and ends with a notification for the user to share the exported file. To be clear, it's not a push-notification, but a Notification
created locally by new NotificationCompat.Builder(…).set…().build()
.
There are quite a lot of users which mute the notification channel (or globally disable notifications for my app). I don't know why, because it's really not very verbose, BTW. But those users feel like the app doesn't work. I'd like to warn them if notifications are muted.
Can I find out up-front whether a particular NotificationChannel
is muted by the user?
I've only found NotificationManager.areNotificationsEnabled()
but I'm not sure if it has another purpose.
回答1:
I believe you can use the combination of both the following methods to detect whether the notifications of a specific channel or the whole package is blocked.
From the Official Document
isBlocked()
public boolean isBlocked ()
Returns whether or not notifications posted to channels belonging to this group are blocked. This value is independent of NotificationManager.areNotificationsEnabled() and NotificationChannel.getImportance().
areNotificationsEnabled()
public boolean areNotificationsEnabled ()
Returns whether notifications from the calling package are blocked.
回答2:
To retrieve a notification channel we can call the method getNotificationChannel()
on the NotificationManager
.
We need to pass the channel_id of the relevant channel.
Also, to retrieve a list of all NotificationChannels
we can invoke the method getNotificationChannels()
.
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
List<NotificationChannel> notificationChannels = notificationManager.getNotificationChannels();
}
Now use your channel id to retrieve properties of that channel from the list. For example: if I created channel with id "Backup alerts"
Then I should check properties of that channels.
If you need to prompt user to adjust settings of that channel: you may trigger an intent from the app itself using Intents like this :
Intent intent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
intent.putExtra(Settings.EXTRA_CHANNEL_ID, notificationChannel.getId());
/*intent.putExtra(Settings.EXTRA_CHANNEL_ID, "Backup alerts");*/
/* Above line is example */
intent.putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName());
startActivity(intent);
We pass the channel id and app package name. This specifically opens the particular channel ID.
Hope that this may help you ;)
来源:https://stackoverflow.com/questions/54198989/find-out-whether-notification-channel-is-muted-by-the-user