下面列出了android.app.NotificationManager#getActiveNotifications ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 如果应用启动的时候通知栏没有关于应用的通知,就删除为通知建立的占位Activity的固定映射关系.
* 将占位activity空出来供其他activity使用
* 但只有6.0及以上系统才有用。4.3到5.1系统需要特殊权限才能访问通知栏,这里不做兼容
*/
private void cleanCacheIfNeeded() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
NotificationManager nm = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
try {
// 1. 目前发现在OPPO R9S PLUST,OPPO R9SK,OPPO R9S,OPPO A57机器上 getActiveNotifications()
// 可能抛出 NullPointerException 导致 Phantom 初始化失败(bugly显示程序都是在后台)
// 2. 双开软件软件会导致 NotificationManager.getActiveNotifications 出现 SecurityException 。例如:
// https://bugly.qq.com/v2/crash-reporting/errors/900016079/201216/report?pid=1
StatusBarNotification[] sbn = null == nm ? null : nm.getActiveNotifications();
VLog.w("cleanCacheIfNeeded active notifications count is %d", null == sbn ? -1 : sbn.length);
if (null != sbn && sbn.length == 0) {
mCache.clean();
}
} catch (Exception e) {
VLog.w(e, "NotificationManager.getActiveNotifications error!");
LogReporter.reportException(e);
}
}
}
private static void cancelActiveNotifications(@NonNull Context context) {
NotificationManager notifications = ServiceUtil.getNotificationManager(context);
notifications.cancel(NotificationIds.MESSAGE_SUMMARY);
if (Build.VERSION.SDK_INT >= 23) {
try {
StatusBarNotification[] activeNotifications = notifications.getActiveNotifications();
for (StatusBarNotification activeNotification : activeNotifications) {
if (!CallNotificationBuilder.isWebRtcNotification(activeNotification.getId())) {
notifications.cancel(activeNotification.getId());
}
}
} catch (Throwable e) {
// XXX Appears to be a ROM bug, see #6043
Log.w(TAG, e);
notifications.cancelAll();
}
}
}
private static boolean isDisplayingSummaryNotification(@NonNull Context context) {
if (Build.VERSION.SDK_INT >= 23) {
try {
NotificationManager notificationManager = ServiceUtil.getNotificationManager(context);
StatusBarNotification[] activeNotifications = notificationManager.getActiveNotifications();
for (StatusBarNotification activeNotification : activeNotifications) {
if (activeNotification.getId() == NotificationIds.MESSAGE_SUMMARY) {
return true;
}
}
return false;
} catch (Throwable e) {
// XXX Android ROM Bug, see #6043
Log.w(TAG, e);
return false;
}
} else {
return false;
}
}
public static void cancel(Context context, int id) {
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
String groupId = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
StatusBarNotification[] activeNotifications = manager.getActiveNotifications();
for (StatusBarNotification activeNotification : activeNotifications) {
if (activeNotification.getId() == id) {
groupId = activeNotification.getNotification().getGroup();
break;
}
}
}
manager.cancel(id);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (groupId != null) {
updateSummaryNotification(context, NotificationUtils.getPackageName(groupId), groupId);
}
}
}
@TargetApi(26) //OREO
private void updateTextFinalOrio(String txt)
{ // Crazy: Android is blocking when too much notification updates, so final message does not receive. Try later :(
int sleepTime = 300;
for (int i=0; i<10; i++)
{
updateTextFinalInternal(txt);
NotificationManager nMgr = (NotificationManager) c.getSystemService(Context.NOTIFICATION_SERVICE);
boolean found = false;
for (StatusBarNotification n : nMgr.getActiveNotifications())
{
if (n.getId() != id) { continue; }
found = true;
if (!n.isOngoing()) { return; }
}
if (!found) { return; }
try { Thread.sleep(sleepTime); } catch (Exception e) {}
sleepTime = (sleepTime/2) * 3;
}
}
@TargetApi(ANDROID_API_MARSHMALLOW)
private static boolean checkUnzipAliveInternal(Context c, MyMap myMap)
{
String unzipKeyId = myMap.getMapName() + "-unzip";
NotificationManager notificationManager = (NotificationManager) c.getSystemService(Context.NOTIFICATION_SERVICE);
for (StatusBarNotification n : notificationManager.getActiveNotifications())
{
if (n.getId() == unzipKeyId.hashCode())
{
long postTime = n.getPostTime();
return timeCheck(postTime);
}
}
return false;
}
public WritableArray getDeliveredNotifications() {
NotificationManager notificationManager = notificationManager();
StatusBarNotification delivered[] = notificationManager.getActiveNotifications();
Log.i(LOG_TAG, "Found " + delivered.length + " delivered notifications");
WritableArray result = Arguments.createArray();
/*
* stay consistent to the return structure in
* https://facebook.github.io/react-native/docs/pushnotificationios.html#getdeliverednotifications
* but there is no such thing as a 'userInfo'
*/
for (StatusBarNotification notification : delivered) {
Notification original = notification.getNotification();
Bundle extras = original.extras;
WritableMap notif = Arguments.createMap();
notif.putString("identifier", "" + notification.getId());
notif.putString("title", extras.getString(Notification.EXTRA_TITLE));
notif.putString("body", extras.getString(Notification.EXTRA_TEXT));
notif.putString("tag", notification.getTag());
notif.putString("group", original.getGroup());
result.pushMap(notif);
}
return result;
}
private static void cancelActiveNotifications(@NonNull Context context) {
NotificationManager notifications = ServiceUtil.getNotificationManager(context);
notifications.cancel(SUMMARY_NOTIFICATION_ID);
if (Build.VERSION.SDK_INT >= 23) {
try {
StatusBarNotification[] activeNotifications = notifications.getActiveNotifications();
for (StatusBarNotification activeNotification : activeNotifications) {
notifications.cancel(activeNotification.getId());
}
} catch (Throwable e) {
// XXX Appears to be a ROM bug, see https://github.com/WhisperSystems/Signal-Android/issues/6043
Log.w(TAG, e);
notifications.cancelAll();
}
}
}
/**
* Returns whether or not there are any download notifications showing that aren't the summary
* notification.
* @param notificationIdToIgnore If not -1, the id of a notification to ignore and
* assume is closing or about to be closed.
* @return Whether or not there are valid download notifications currently visible.
*/
@TargetApi(Build.VERSION_CODES.M)
private static boolean hasDownloadNotifications(
NotificationManager manager, int notificationIdToIgnore) {
if (!useForegroundService()) return false;
StatusBarNotification[] notifications = manager.getActiveNotifications();
for (StatusBarNotification notification : notifications) {
boolean isDownloadsGroup = TextUtils.equals(notification.getNotification().getGroup(),
NotificationConstants.GROUP_DOWNLOADS);
boolean isSummaryNotification =
notification.getId() == NotificationConstants.NOTIFICATION_ID_DOWNLOAD_SUMMARY;
boolean isIgnoredNotification =
notificationIdToIgnore != -1 && notificationIdToIgnore == notification.getId();
if (isDownloadsGroup && !isSummaryNotification && !isIgnoredNotification) return true;
}
return false;
}
/**
* @return The summary {@link StatusBarNotification} if one is showing.
*/
@TargetApi(Build.VERSION_CODES.M)
private static StatusBarNotification getSummaryNotification(NotificationManager manager) {
if (!useForegroundService()) return null;
StatusBarNotification[] notifications = manager.getActiveNotifications();
for (StatusBarNotification notification : notifications) {
boolean isDownloadsGroup = TextUtils.equals(notification.getNotification().getGroup(),
NotificationConstants.GROUP_DOWNLOADS);
boolean isSummaryNotification =
notification.getId() == NotificationConstants.NOTIFICATION_ID_DOWNLOAD_SUMMARY;
if (isDownloadsGroup && isSummaryNotification) return notification;
}
return null;
}
private static void cancelOrphanedNotifications(@NonNull Context context, NotificationState notificationState) {
if (Build.VERSION.SDK_INT >= 23) {
try {
NotificationManager notifications = ServiceUtil.getNotificationManager(context);
StatusBarNotification[] activeNotifications = notifications.getActiveNotifications();
for (StatusBarNotification notification : activeNotifications) {
boolean validNotification = false;
if (notification.getId() != NotificationIds.MESSAGE_SUMMARY &&
notification.getId() != KeyCachingService.SERVICE_RUNNING_ID &&
notification.getId() != IncomingMessageObserver.FOREGROUND_ID &&
notification.getId() != NotificationIds.PENDING_MESSAGES &&
!CallNotificationBuilder.isWebRtcNotification(notification.getId()))
{
for (NotificationItem item : notificationState.getNotifications()) {
if (notification.getId() == NotificationIds.getNotificationIdForThread(item.getThreadId())) {
validNotification = true;
break;
}
}
if (!validNotification) {
notifications.cancel(notification.getId());
}
}
}
} catch (Throwable e) {
// XXX Android ROM Bug, see #6043
Log.w(TAG, e);
}
}
}
private void updateCurrentNotifications(NotificationFetchData notificationFetchData, NotificationManager notificationManager, Context context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return;
}
// This try-catch is needed because of an Android 6.0 issue where calling getActiveNotifications may throw a nullpointerexception
// https://github.com/googlesamples/android-ActiveNotifications/issues/1
try {
if (notificationManager == null || notificationManager.getActiveNotifications() == null) {
return;
}
} catch (NullPointerException e) {
return;
}
// Nested for loops :/
for (StatusBarNotification statusBarNotification : notificationManager.getActiveNotifications()) {
for (StreamInfo stream : notificationFetchData.getCurrentlyOnlineStreams()) {
if (stream.getChannelInfo().getNotificationTag().equals(statusBarNotification.getTag())) {
Notification notification = createStreamNotification(
stream,
getLargeIconFromNotification(statusBarNotification.getNotification(), context),
true,
context
);
notificationManager.notify(
stream.getChannelInfo().getNotificationTag(),
NOTIFICATION_ID,
notification
);
}
}
}
}
public boolean notificationExists(int notificationId) {
NotificationManager notificationManager = (NotificationManager)
this.context.getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= 23) {
StatusBarNotification[] notifications = notificationManager
.getActiveNotifications();
for (StatusBarNotification notification : notifications)
if (notification.getId() == notificationId)
return true;
return false;
}
//If lacks support
return true;
}
public void removeIncomingCallNotification(ReactApplicationContext context,
CallInvite callInvite,
int notificationId) {
Log.d(TAG, "removeIncomingCallNotification");
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
if (callInvite != null && callInvite.getState() == CallInvite.State.PENDING) {
/*
* If the incoming call message was cancelled then remove the notification by matching
* it with the call sid from the list of notifications in the notification drawer.
*/
StatusBarNotification[] activeNotifications = notificationManager.getActiveNotifications();
for (StatusBarNotification statusBarNotification : activeNotifications) {
Notification notification = statusBarNotification.getNotification();
String notificationType = notification.extras.getString(NOTIFICATION_TYPE);
if (callInvite.getCallSid().equals(notification.extras.getString(CALL_SID_KEY)) &&
notificationType != null && notificationType.equals(ACTION_INCOMING_CALL)) {
notificationManager.cancel(notification.extras.getInt(INCOMING_CALL_NOTIFICATION_ID));
}
}
} else if (notificationId != 0) {
notificationManager.cancel(notificationId);
}
} else {
if (notificationId != 0) {
notificationManager.cancel(notificationId);
} else if (callInvite != null) {
String notificationKey = INCOMING_NOTIFICATION_PREFIX+callInvite.getCallSid();
if (TwilioVoiceModule.callNotificationMap.containsKey(notificationKey)) {
notificationId = TwilioVoiceModule.callNotificationMap.get(notificationKey);
notificationManager.cancel(notificationId);
TwilioVoiceModule.callNotificationMap.remove(notificationKey);
}
}
}
}
private static void cancelOrphanedNotifications(@NonNull Context context, NotificationState notificationState) {
if (Build.VERSION.SDK_INT >= 23) {
try {
NotificationManager notifications = ServiceUtil.getNotificationManager(context);
StatusBarNotification[] activeNotifications = notifications.getActiveNotifications();
for (StatusBarNotification notification : activeNotifications) {
boolean validNotification = false;
if (notification.getId() != SUMMARY_NOTIFICATION_ID) {
for (NotificationItem item : notificationState.getNotifications()) {
if (notification.getId() == (SUMMARY_NOTIFICATION_ID + item.getThreadId())) {
validNotification = true;
break;
}
}
if (!validNotification) {
notifications.cancel(notification.getId());
}
}
}
} catch (Throwable e) {
// XXX Android ROM Bug, see https://github.com/WhisperSystems/Signal-Android/issues/6043
Log.w(TAG, e);
}
}
}
@Override
public void onReceive(Context context, Intent intent) {
//PPApplication.logE("##### NotUsedMobileCellsNotificationDisableReceiver.onReceive", "xxx");
//CallsCounter.logCounter(context, "NotUsedMobileCellsNotificationDisableReceiver.onReceive", "NotUsedMobileCellsNotificationDisableReceiver_onReceive");
SharedPreferences.Editor editor = ApplicationPreferences.getEditor(context.getApplicationContext());
editor.putBoolean(ApplicationPreferences.PREF_APPLICATION_EVENT_MOBILE_CELL_NOT_USED_CELLS_DETECTION_NOTIFICATION_ENABLED, false);
editor.apply();
ApplicationPreferences.applicationEventMobileCellNotUsedCellsDetectionNotificationEnabled(context.getApplicationContext());
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (manager != null) {
//if (Build.VERSION.SDK_INT >= 23) {
StatusBarNotification[] notifications = manager.getActiveNotifications();
for (StatusBarNotification notification : notifications) {
String tag = notification.getTag();
if ((tag != null) && tag.contains(PPApplication.NEW_MOBILE_CELLS_NOTIFICATION_TAG+"_")) {
if (notification.getId() >= PPApplication.NEW_MOBILE_CELLS_NOTIFICATION_ID) {
manager.cancel(notification.getTag(), notification.getId());
}
}
}
/*} else {
int notificationId = intent.getIntExtra("notificationId", 0);
manager.cancel(notificationId);
}*/
}
}
static void removeProfileNotification(Context context)
{
try {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null) {
notificationManager.cancel(
PPApplication.GRANT_PROFILE_PERMISSIONS_NOTIFICATION_TAG,
PPApplication.GRANT_PROFILE_PERMISSIONS_NOTIFICATION_ID);
//if (Build.VERSION.SDK_INT >= 23) {
StatusBarNotification[] notifications = notificationManager.getActiveNotifications();
for (StatusBarNotification notification : notifications) {
String tag = notification.getTag();
if ((tag != null) && tag.contains(PPApplication.GRANT_PROFILE_PERMISSIONS_NOTIFICATION_TAG+"_")) {
if (notification.getId() >= PPApplication.PROFILE_ID_NOTIFICATION_ID) {
notificationManager.cancel(notification.getTag(), notification.getId());
}
}
}
/*} else {
int notificationId = intent.getIntExtra("notificationId", 0);
manager.cancel(notificationId);
}*/
}
} catch (Exception e) {
PPApplication.recordException(e);
}
}
static void removeEventNotification(Context context)
{
try {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null) {
notificationManager.cancel(
PPApplication.GRANT_EVENT_PERMISSIONS_NOTIFICATION_TAG,
PPApplication.GRANT_EVENT_PERMISSIONS_NOTIFICATION_ID);
//if (Build.VERSION.SDK_INT >= 23) {
StatusBarNotification[] notifications = notificationManager.getActiveNotifications();
for (StatusBarNotification notification : notifications) {
String tag = notification.getTag();
if ((tag != null) && tag.contains(PPApplication.GRANT_EVENT_PERMISSIONS_NOTIFICATION_TAG+"_")) {
if (notification.getId() >= PPApplication.EVENT_ID_NOTIFICATION_ID) {
notificationManager.cancel(notification.getTag(), notification.getId());
}
}
}
/*} else {
int notificationId = intent.getIntExtra("notificationId", 0);
manager.cancel(notificationId);
}*/
}
} catch (Exception e) {
PPApplication.recordException(e);
}
}
private void cancelAlarmNotification(Context context)
{
NotificationManager mNotifyMgr = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
StatusBarNotification[] activeNotifications = mNotifyMgr.getActiveNotifications();
for (StatusBarNotification notification : activeNotifications)
{
if (notification.getId() == ALARM_NOTIFICATION_ID) mNotifyMgr.cancel(ALARM_NOTIFICATION_ID);
}
}
else mNotifyMgr.cancel(ALARM_NOTIFICATION_ID);
}
@TargetApi(Build.VERSION_CODES.N)
private static void updateSummaryNotification(Context context, String packageName, String groupId) {
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
StatusBarNotification[] activeNotifications = manager.getActiveNotifications();
int notificationCntInGroup = 0;
for (StatusBarNotification statusBarNotification : activeNotifications) {
if (groupId.equals(statusBarNotification.getNotification().getGroup())) {
notificationCntInGroup++;
}
}
if (notificationCntInGroup > 1) {
CharSequence appName = ApplicationNameCache.getInstance().getAppName(context, packageName);
Bundle extras = new Bundle();
Notification.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder = new Notification.Builder(context, getChannelIdByPkg(packageName));
builder.setGroupAlertBehavior(Notification.GROUP_ALERT_CHILDREN);
} else {
builder = new Notification.Builder(context);
}
int color = getIconColor(context, packageName);
if (color != Notification.COLOR_DEFAULT) {
CharSequence subText = ColorUtil.createColorSubtext(appName, color);
if (subText != null) {
extras.putCharSequence(NotificationCompat.EXTRA_SUB_TEXT, subText);
}
builder.setColor(color);
} else {
extras.putCharSequence(NotificationCompat.EXTRA_SUB_TEXT, appName);
}
builder.setExtras(extras);
// Set small icon
NotificationController.processSmallIcon(context, packageName, builder);
builder.setCategory(Notification.CATEGORY_EVENT)
.setGroupSummary(true)
.setGroup(groupId);
Notification notification = builder.build();
manager.notify(packageName.hashCode(), notification);
} else {
manager.cancel(packageName.hashCode());
}
}