下面列出了android.support.annotation.RestrictTo#android.service.notification.StatusBarNotification 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
Bundle extras = sbn.getNotification().extras;
String title = extras.getString("android.title");
String text = extras.getCharSequence("android.text").toString();
String pack = sbn.getPackageName();
CharSequence ticker = sbn.getNotification().tickerText;
boolean ongoing = sbn.isOngoing();
boolean clearable = sbn.isClearable();
Intent msgrcv = new Intent("Msg");
msgrcv.putExtra("title", title);
msgrcv.putExtra("text", text);
msgrcv.putExtra("p", pack);
msgrcv.putExtra("c", clearable);
msgrcv.putExtra("o", ongoing);
msgrcv.putExtra("t", String.valueOf(ticker));
LocalBroadcastManager.getInstance(context).sendBroadcast(msgrcv);
}
protected boolean cancel(int userId, String pkg, String tag, int id) {
if (mSnoozedNotifications.containsKey(userId)) {
ArrayMap<String, NotificationRecord> recordsForPkg =
mSnoozedNotifications.get(userId).get(pkg);
if (recordsForPkg != null) {
final Set<Map.Entry<String, NotificationRecord>> records = recordsForPkg.entrySet();
String key = null;
for (Map.Entry<String, NotificationRecord> record : records) {
final StatusBarNotification sbn = record.getValue().sbn;
if (Objects.equals(sbn.getTag(), tag) && sbn.getId() == id) {
record.getValue().isCanceled = true;
return true;
}
}
}
}
return false;
}
/**
* Dismisses given notification from system and app.
*/
@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
public static void dismissNotification(@NonNull OpenNotification n) {
NotificationPresenter.getInstance().removeNotification(n);
StatusBarNotification sbn = n.getStatusBarNotification();
if (sbn != null && Device.hasJellyBeanMR2Api()) {
MediaService service = MediaService.sService;
if (service != null) {
if (Device.hasLollipopApi()) {
service.cancelNotification(sbn.getKey());
} else {
service.cancelNotification(
sbn.getPackageName(),
sbn.getTag(),
sbn.getId());
}
} else {
Log.e(TAG, "Failed to dismiss notification because notification service is offline.");
}
}
}
private void broadcastNotificationCount() {
int count = 0;
StatusBarNotification[] notifications;
try {
notifications = getActiveNotifications();
} catch (SecurityException e) {
notifications = new StatusBarNotification[0];
}
for(StatusBarNotification notification : notifications) {
if((notification.getNotification().flags & NotificationCompat.FLAG_GROUP_SUMMARY) == 0
&& notification.isClearable()) count++;
}
broadcastNotificationCount(count);
}
private void sendBroadcastToHomeScreenActivity() {
try {
final StatusBarNotification[] statusBarNotifications = getActiveNotifications();
final ArrayList<String> packages = new ArrayList<>(statusBarNotifications.length);
for (final StatusBarNotification statusBarNotification : statusBarNotifications) {
packages.add(statusBarNotification.getPackageName());
}
final Intent intent = new Intent(HOME_SCREEN_ACTIVITY_BROADCAST)
.putExtra("amount", statusBarNotifications.length)
.putStringArrayListExtra("packages", packages);
LocalBroadcastManager.getInstance(this)
.sendBroadcast(intent);
} catch (SecurityException e) {
Log.e(TAG, e.getMessage());
e.printStackTrace();
}
}
private boolean checkAppSwitch(OnlineConfig onlineConfig, StatusBarNotification statusBarNotification) {
boolean z = true;
String stringValue = onlineConfig.getStringValue(ConfigKey.CollectionNotificationInfoAppSwitch.getValue(), "b");
if (TextUtils.isEmpty(stringValue)) {
return false;
}
List emptyList = Collections.emptyList();
if (stringValue.length() > 1) {
emptyList = Arrays.asList(stringValue.substring(1).split(";"));
}
String packageName = statusBarNotification.getPackageName();
char charAt = stringValue.charAt(0);
if (charAt != 'b') {
return charAt == 'w' ? emptyList.contains(packageName) : false;
} else {
if (emptyList.contains(packageName)) {
z = false;
}
return z;
}
}
private ProgressInfo verifyNotification(StatusBarNotification statusBarNotif) {
if (statusBarNotif == null)
return null;
String id = getIdentifier(statusBarNotif);
if (id == null)
return null;
Notification n = statusBarNotif.getNotification();
if (n != null &&
(SUPPORTED_PACKAGES.contains(statusBarNotif.getPackageName()) ||
n.extras.getBoolean(ModLedControl.NOTIF_EXTRA_PROGRESS_TRACKING))) {
ProgressInfo pi = getProgressInfo(id, n);
if (pi != null && pi.hasProgressBar)
return pi;
}
return null;
}
public static boolean shouldDisplayNotification(StatusBarNotification oldNotif,
StatusBarNotification newNotif) {
// First check for ticker text, if they are different, some other parameters will be
// checked to determine if we should show the notification.
CharSequence oldTickerText = oldNotif.getNotification().tickerText;
CharSequence newTickerText = newNotif.getNotification().tickerText;
if (newTickerText == null ? oldTickerText == null : newTickerText.equals(oldTickerText)) {
// If old notification title isn't null, show notification if
// new notification title is different. If it is null, show notification
// if the new one isn't.
String oldNotificationText = getNotificationTitle(oldNotif);
String newNotificationText = getNotificationTitle(newNotif);
if (newNotificationText == null ? oldNotificationText != null : !newNotificationText
.equals(oldNotificationText)) {
return true;
}
// Last chance, check when the notifications were posted. If times
// are equal, we shouldn't display the new notification.
if (oldNotif.getNotification().when != newNotif.getNotification().when) {
return true;
}
return false;
}
return true;
}
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
if (Log.isPrint) {
Log.i(TAG, sbn.toString());
Notification notification = sbn.getNotification();
Log.i(TAG, "tickerText : " + notification.tickerText);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Bundle bundle = notification.extras;
for (String key : bundle.keySet()) {
Log.i(TAG, key + ": " + bundle.get(key));
}
}
}
if (self != null && notificationListener != null) {
notificationListener.onNotificationPosted(sbn);
}
}
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getStringExtra("command").equals("clearall")){
NotificationReceiverService.this.cancelAllNotifications();
}
else if(intent.getStringExtra("command").equals("list")){
for (StatusBarNotification sbn : NotificationReceiverService.this.getActiveNotifications()) {
Intent i2 = new Intent(Constants.NOTIFICATION_LISTENER);
i2.putExtra(NOTIFICATION_KEY_CMD, NOTIFICATION_CMD_LIST);
i2.putExtra(NOTIFICATION_KEY_ID, sbn.getId());
i2.putExtra(NOTIFICATION_KEY_PACKAGE, sbn.getPackageName());
i2.putExtra(NOTIFICATION_KEY_TEXT, sbn.getNotification().tickerText);
sendBroadcast(i2);
}
}
}
@RequiresApi(Build.VERSION_CODES.KITKAT)
private void extractTitle(StatusBarNotification sbn, PackageManager pm) {
Bundle extras = sbn.getNotification().extras;
String contentTitle = "";
CharSequence temp = extras.getCharSequence(android.app.Notification.EXTRA_TITLE);
if (temp != null){
contentTitle = temp.toString();
}
String appName = getAppName(pm, sbn.getPackageName());
title = "";
if (ns.forceTitle()){
title = appName;
} else {
if (!contentTitle.equals("")){
title = contentTitle;
} else {
title = appName;
}
}
title = title.trim();
}
@Override
public boolean handleMessage(Message message) {
switch (message.what) {
case MSG_NOTIFICATION_POSTED:
if (sNotificationsChangedListener != null) {
NotificationPostedMsg msg = (NotificationPostedMsg) message.obj;
sNotificationsChangedListener.onNotificationPosted(msg.packageUserKey,
msg.notificationKey, msg.shouldBeFilteredOut);
}
break;
case MSG_NOTIFICATION_REMOVED:
if (sNotificationsChangedListener != null) {
Pair<PackageUserKey, NotificationKeyData> pair
= (Pair<PackageUserKey, NotificationKeyData>) message.obj;
sNotificationsChangedListener.onNotificationRemoved(pair.first, pair.second);
}
break;
case MSG_NOTIFICATION_FULL_REFRESH:
if (sNotificationsChangedListener != null) {
sNotificationsChangedListener.onNotificationFullRefresh(
(List<StatusBarNotification>) message.obj);
}
break;
}
return true;
}
void init(final @NonNull Context context,
final @NonNull StatusBarNotification[] activeNotifications) {
mHandler.post(new Runnable() {
@SuppressLint("NewApi")
@Override
public void run() {
clear(false);
if (DEBUG) Log.d(TAG, "Initializing the notifications list...");
// Initialize the notifications list through the proxy to
// optimize the process. This is completely not useful on
// pre-Lollipop devices due to lack of children notifications.
List<NotificationPrTask> list = new ArrayList<>(activeNotifications.length);
for (StatusBarNotification sbn : activeNotifications) {
OpenNotification n = OpenNotification.newInstance(sbn);
list.add(new NotificationPrTask(context, n, true /* post */, 0));
}
if (Device.hasLollipopApi()) mProxy.optimizePrTasks(list);
mProxy.sendPrTasks(list);
list.clear(); // This is probably not needed.
}
});
}
/**
* 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;
}
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
Log.d(TAG, "Notification received: "+sbn.getPackageName()+":"+sbn.getNotification().tickerText);
if (sbn.getNotification().tickerText == null) {
return;
}
WritableNativeMap params = new WritableNativeMap();
params.putString("text", sbn.getNotification().tickerText.toString());
String app = sbn.getPackageName();
if (app.equals(NotificationModule.smsApp)) {
params.putString("app", "sms");
} else {
params.putString("app", app);
}
NotificationModule.sendEvent("notificationReceived", params);
}
/**
* Called when notifications are removed
*/
@Override
public void onNotificationRemoved(StatusBarNotification sbn) {
Intent intent = new Intent(NOTIFICATION_UPDATE);
intent.putExtra(NotificationKey.ACTION, NotificationAction.NOTIFICATION_REMOVED);
intent.putExtra(NotificationKey.APPLICATION_PACKAGE_NAME,sbn.getPackageName());
// List the notifications in a string array
StatusBarNotification[] activeNotifications = NotificationService.this.getActiveNotifications();
String packages[] = new String[activeNotifications.length];
int i = 0;
for (StatusBarNotification nf : activeNotifications) {
packages[i++] = nf.getPackageName();
}
intent.putExtra(NotificationKey.APPLICATION_PACKAGES, packages);
// Broadcast the intent
sendBroadcast(intent);
numNotifications = packages.length;
}
@Override
public void onNotificationRemoved(@Nullable StatusBarNotification sbn) {
if (sbn == null) {
logger.log(LogLevel.WARNING, LOG_TAG, "onNotificationRemoved: StatusBarNotification is null");
return;
}
logger.log(LogLevel.VERBOSE, LOG_TAG, "onNotificationRemoved: [%s]\t%s", sbn.getId(), sbn.getPackageName());
ZephyrExecutors.getDiskExecutor().execute(() -> {
if (isValidNotification(sbn)) {
DismissNotificationPayload dismissNotificationPayload = new DismissNotificationPayload();
dismissNotificationPayload.packageName = sbn.getPackageName();
dismissNotificationPayload.id = sbn.getId();
logger.log(LogLevel.VERBOSE, LOG_TAG, "Dismissing notification: %s", sbn.getId());
EventBus.getDefault().post(dismissNotificationPayload);
}
});
}
/**
* Un-autogroups notifications that are now grouped by the app.
*/
private void maybeUngroup(StatusBarNotification sbn, boolean notificationGone, int userId) {
List<String> notificationsToUnAutogroup = new ArrayList<>();
boolean removeSummary = false;
synchronized (mUngroupedNotifications) {
Map<String, LinkedHashSet<String>> ungroupedNotificationsByUser
= mUngroupedNotifications.get(sbn.getUserId());
if (ungroupedNotificationsByUser == null || ungroupedNotificationsByUser.size() == 0) {
return;
}
LinkedHashSet<String> notificationsForPackage
= ungroupedNotificationsByUser.get(sbn.getPackageName());
if (notificationsForPackage == null || notificationsForPackage.size() == 0) {
return;
}
if (notificationsForPackage.remove(sbn.getKey())) {
if (!notificationGone) {
// Add the current notification to the ungrouping list if it still exists.
notificationsToUnAutogroup.add(sbn.getKey());
}
}
// If the status change of this notification has brought the number of loose
// notifications to zero, remove the summary and un-autogroup.
if (notificationsForPackage.size() == 0) {
ungroupedNotificationsByUser.remove(sbn.getPackageName());
removeSummary = true;
}
}
if (removeSummary) {
adjustAutogroupingSummary(userId, sbn.getPackageName(), null, false);
}
if (notificationsToUnAutogroup.size() > 0) {
adjustNotificationBundling(notificationsToUnAutogroup, false);
}
}
public static StatusBarNotification[] getActiveNotifications(NotificationManager manager) {
if (Version.sdkAboveOrEqual(Version.API23_MARSHMALLOW_60)) {
return ApiTwentyThreePlus.getActiveNotifications(manager);
}
return new StatusBarNotification[0];
}
private boolean isValidNotification(@NonNull StatusBarNotification sbn) {
if (sbn.getPackageName().equals(BuildConfig.APPLICATION_ID)) {
logger.log(LogLevel.DEBUG, LOG_TAG, "Invalid notification: Zephyr");
return false;
}
if (!sbn.isClearable()) {
logger.log(LogLevel.DEBUG, LOG_TAG, "Invalid notification: Not clearable");
return false;
}
if (getPackageManager().getLaunchIntentForPackage(sbn.getPackageName()) == null) {
logger.log(LogLevel.DEBUG, LOG_TAG, "Invalid notification: No launch intent");
return false;
}
INotificationPreference notificationPreference = notificationPreferenceRepository.getNotificationPreferenceSync(sbn.getPackageName());
if (notificationPreference == null) {
logger.log(LogLevel.DEBUG, LOG_TAG, "Invalid notification: null preference");
return false;
}
if (!notificationPreference.isEnabled()) {
logger.log(LogLevel.DEBUG, LOG_TAG, "Invalid notification: Disabled");
return false;
}
logger.log(LogLevel.DEBUG, LOG_TAG, "Valid notification.");
return true;
}
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
super.onNotificationPosted(sbn);
Log.d(TAG, "onNotificationPosted");
Notification notification = sbn.getNotification();
String packageName = sbn.getPackageName();
long time = sbn.getPostTime();
String title = notification.extras.getString(Notification.EXTRA_TITLE);
String text = notification.extras.getString(Notification.EXTRA_TEXT);
DbUtils.saveNotification(new NotificationInfo(packageName, title, text, time));
List<AppInfo> blackList = DbUtils.getApp();
for (AppInfo app : blackList) {
if (packageName.equals(app.getPackageName())) {
Log.d(TAG, packageName + " 拦截:" + title + ": " + text);
if (android.os.Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
cancelNotification(sbn.getKey());
} else {
cancelNotification(sbn.getPackageName(), sbn.getTag(), sbn.getId());
}
if (SettingUtils.getInstance().isNotify()) {
createNotification(app.getAppName(), packageName, title, text);
}
}
}
}
public void removeNotification(StatusBarNotification n) {
for (int i = 0; i < mShownNotifications.size(); i++) {
if (NotificationHelper.getContentDescription(n)
.equals(NotificationHelper.getContentDescription(mShownNotifications.get(i)))) {
mShownNotifications.remove(i);
i--;
}
}
updateNotificationIcons();
}
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);
}
}
}
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
@Override
public void onListenerConnected(@NonNull NotificationListenerService service) {
StatusBarNotification[] an = service.getActiveNotifications();
if (an == null) return;
NotificationPresenter np = NotificationPresenter.getInstance();
np.init(service, an);
}
/**
* Retrieve historic notifications posted with the given key (including the incoming one without decoration at the last).
* The number of notifications kept in archive is undefined.
*
* Decorator permission restriction applies.
*/
protected final List<StatusBarNotification> getArchivedNotifications(final String key, final int limit) {
try {
return mController.getNotifications(mWrapper, TYPE_ARCHIVED, singletonList(key), limit, null);
} catch (final RemoteException e) {
Log.w(TAG, "Error retrieving archived notifications: " + key, e);
return Collections.emptyList();
}
}
public static StatusBarNotification[] getAllActiveNotifications() {
if(instance != null) {
try {
return instance.getActiveNotifications();
} catch (Exception e) {
if(Const.DEBUG) e.printStackTrace();
}
}
return null;
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
@NonNull
static OpenNotification newInstance(@NonNull StatusBarNotification sbn) {
Notification n = sbn.getNotification();
if (Device.hasLollipopApi()) {
return new OpenNotificationLollipop(sbn, n);
} else if (Device.hasKitKatWatchApi()) {
return new OpenNotificationKitKatWatch(sbn, n);
}
return new OpenNotificationJellyBeanMR2(sbn, n);
}
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
private boolean postActiveNotifications(@NonNull NotificationListenerService service) {
StatusBarNotification[] an = service.getActiveNotifications();
if (an == null) return false;
NotificationPresenter np = NotificationPresenter.getInstance();
np.init(service, an);
return mInitialized = true;
}
@Override
public void onNotificationDataChanged(final StatusBarNotification sbn) {
for (AppInfo ai : mAppSlots) {
if (ai.getPackageName() == null)
continue;
if (sbn == null || sbn.getPackageName() == null ||
sbn.getPackageName().equals(ai.getPackageName())) {
ai.updateIcon();
}
}
}
@Override
public void onNotificationRemoved(StatusBarNotification statusnotification) {
Log.d(TAG, "Cleaning up notifications");
Message msg = new Message();
msg.obj = statusnotification;
msg.arg1 = 1;
mHandler.sendMessage(msg);
}