我正在开发接收推送通知的 Android 应用程序。我也在不同的论坛中搜索了很多答案,但没有找到适合这个问题的解决方案。我什至也尝试过改变Notification ID
,以免受到多次推动。我用过Intent.FLAG_ACTIVITY_CLEAR_TOP
,但效果不佳。
我的代码:
public void showNotificationMessage(String title, String message, Intent intent) {
// Check for empty push message
if (TextUtils.isEmpty(message))
return;
if (isAppIsInBackground(mContext)) {
// notification icon
int icon = R.mipmap.ic_logo;
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
mContext,
0,
intent,
PendingIntent.FLAG_CANCEL_CURRENT
);
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
mContext);
Notification notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
.setAutoCancel(true)
.setContentTitle(title)
.setStyle(inboxStyle)
.setContentIntent(resultPendingIntent)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
.setContentText(message)
.build();
mBuilder.setContentIntent(contentIntent);
NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(count++, notification);
} else {
intent.putExtra("title", title);
intent.putExtra("message", message);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
mContext.startActivity(intent);
}
}