当我在应用程序中使用FCM推送通知时,每当通知在状态栏中显示最新的通知时,我都希望显示所有通知,直到用户单击为止。如果我使用挂起的intent。Flag_current表示它在android中显示最新的通知请帮助我。
服务:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();
private NotificationUtils notificationUtils;
AlertDialog alertDialog = null;
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// Log.e("BB", "From: " + remoteMessage.getNotification().getBody());
// Log.e("BB", "From-: " + remoteMessage.getNotification());
if (remoteMessage == null)
return;
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.e("BB", "remoteMessage.getData().toString() " + remoteMessage.getData().toString());
handleNotification(remoteMessage.getNotification().getBody());
}
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());
// Log.e(TAG, "Data Payload---: " + remoteMessage.getNotification().toString());
try {
JSONObject json = new JSONObject(remoteMessage.getData().toString());
handleDataMessage(json);
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
}
}
private void handleNotification(String message) {
if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
// app is in foreground, broadcast the push message
Log.e("BB", "iff: " +message);
Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
pushNotification.putExtra("message", message);
LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
// showNotificationMessage(getApplicationContext(), "", message, "", pushNotification, roleid, clickmessage);
// play notification sound
NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
// notificationUtils.playNotificationSound();
}else{
Log.e("BB", "else: " +message);
// play notification sound
NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
notificationUtils.playNotificationSound();
// If the app is in background, firebase itself handles the notification
}
}
private void handleDataMessage(JSONObject json) {
Log.e(TAG, "push json: " + json.toString());
try {
JSONObject data = json.getJSONObject("data");
String title = data.getString("body");
String message = data.getString("body");
String roleid = data.getString("role_Id");
String clickmessage = data.getString("click_action");
// boolean isBackground = data.getBoolean("is_background");
//String imageUrl = data.getString("image");
// String timestamp = data.getString("timestamp");
// JSONObject payload = data.getJSONObject("payload");
/* Log.e(TAG, "title: " + title);
Log.e(TAG, "message: " + message);
Log.e(TAG, "isBackground: " + isBackground);
Log.e(TAG, "payload: " + payload.toString());
Log.e(TAG, "imageUrl: " + imageUrl);
Log.e(TAG, "timestamp: " + timestamp);*/
if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
// app is in foreground, broadcast the push message
Log.e("BB", "iff: " + title+message);
Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
pushNotification.putExtra("message", message);
LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
// play notification sound
NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
//notificationUtils.playNotificationSound();
showNotificationMessage(getApplicationContext(), title, message, "", pushNotification,roleid,clickmessage);
/* if (TextUtils.isEmpty(imageUrl)) {
} else {
// image is present, show notification with image
showNotificationMessageWithBigImage(getApplicationContext(), title, message, "", pushNotification, "");
}*/
} else {
Log.e("BB", "elsee: " + title+message);
Intent pushNotification = new Intent(Config.PUSH_NOTIFICATION);
pushNotification.putExtra("message", message);
LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
showNotificationMessage(getApplicationContext(), title, message, "", pushNotification,roleid,clickmessage);
}
} catch (JSONException e) {
Log.e(TAG, "Json Exception: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
}
/**
* Showing notification with text only
*/
private void showNotificationMessage(Context context, String title, String message, String timeStamp, Intent intent, String roleid, String clickmessage) {
notificationUtils = new NotificationUtils(context);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
notificationUtils.showNotificationMessage(title, message, timeStamp, intent,roleid,clickmessage);
}
/**
* Showing notification with text and image
*/
private void showNotificationMessageWithBigImage(Context context, String title, String message, String timeStamp, Intent intent, String imageUrl,String roleid, String clickmessage) {
notificationUtils = new NotificationUtils(context);
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
notificationUtils.showNotificationMessage(title, message, timeStamp, intent, imageUrl,roleid,clickmessage);
}
}
通知实用程序:
public class NotificationUtils {
private static String TAG = NotificationUtils.class.getSimpleName();
private Context mContext;
public NotificationUtils(Context mContext) {
this.mContext = mContext;
}
public void showNotificationMessage(String title, String message, String timeStamp, Intent intent, String roleid, String clickmessage) {
showNotificationMessage(title, message, timeStamp, intent, null,roleid,clickmessage);
}
public void showNotificationMessage(final String title, final String message, final String timeStamp, Intent intent, String imageUrl,String roleid, String clickmessage) {
// Check for empty push message
if (TextUtils.isEmpty(message))
return;
// notification icon
final int icon = R.drawable.getspot_logo;
if(roleid.equalsIgnoreCase("5"))
{
intent = new Intent(mContext, ManagerHomePage.class);
Bundle bundle = new Bundle();
bundle.putString("fromwhere",clickmessage);
intent.putExtras(bundle);
}
else {
intent = new Intent(mContext, UserHomePage.class);
Bundle bundle = new Bundle();
bundle.putString("fromwhere",clickmessage);
intent.putExtras(bundle);
}
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
/* final PendingIntent resultPendingIntent =
PendingIntent.getActivity(
mContext,
0,
intent,
PendingIntent.FLAG_CANCEL_CURRENT
);*/
TaskStackBuilder stackBuilder = TaskStackBuilder.create(mContext);
stackBuilder.addNextIntentWithParentStack(intent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_ONE_SHOT);
final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
mContext);
final Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
+ "://" + mContext.getPackageName() + "/raw/notification");
if (!TextUtils.isEmpty(imageUrl)) {
if (imageUrl != null && imageUrl.length() > 4 && Patterns.WEB_URL.matcher(imageUrl).matches()) {
Bitmap bitmap = getBitmapFromURL(imageUrl);
if (bitmap != null) {
showBigNotification(bitmap, mBuilder, icon, title, message, timeStamp, resultPendingIntent, alarmSound);
} else {
showSmallNotification(mBuilder, icon, title, message, timeStamp, resultPendingIntent, alarmSound);
}
}
} else {
showSmallNotification(mBuilder, icon, title, message, timeStamp, resultPendingIntent, alarmSound);
// playNotificationSound();
}
}
private void showSmallNotification(NotificationCompat.Builder mBuilder, int icon, String title, String message, String timeStamp, PendingIntent resultPendingIntent, Uri alarmSound) {
int notifyID = 1;
String CHANNEL_ID = "my_channel_01";// The id of the channel.
CharSequence name = "Product";// The user-visible name of the channel.
int importance = NotificationManager.IMPORTANCE_HIGH;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
Log.i("RR","----");
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
// Create a notification and set the notification channel.
Notification notification = new Notification.Builder(mContext)
.setContentTitle("Notification")
.setContentText(message)
.setSmallIcon(R.drawable.getspot_logo)
.setChannelId(CHANNEL_ID)
.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
.setContentIntent(resultPendingIntent)
.setAutoCancel(true)
.build();
mBuilder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL;
NotificationManager mNotificationManager =
(NotificationManager)mContext. getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.createNotificationChannel(mChannel);
// Issue the notification.
mNotificationManager.notify(notifyID , notification);
}
Log.i("RR","elsee----");
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
inboxStyle.addLine(message);
Notification notification;
notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
.setAutoCancel(true)
.setContentTitle("Notification")
.setContentIntent(resultPendingIntent)
.setSound(alarmSound)
.setStyle(inboxStyle)
.setSmallIcon(R.drawable.getspot_logo)
.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
.setContentText(message)
.build();
// mBuilder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL;
NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(Config.NOTIFICATION_ID, notification);
}
private void showBigNotification(Bitmap bitmap, NotificationCompat.Builder mBuilder, int icon, String title, String message, String timeStamp, PendingIntent resultPendingIntent, Uri alarmSound) {
NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
bigPictureStyle.setBigContentTitle(title);
bigPictureStyle.setSummaryText(Html.fromHtml(message).toString());
bigPictureStyle.bigPicture(bitmap);
Notification notification;
notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
.setAutoCancel(true)
.setContentTitle(title)
.setContentIntent(resultPendingIntent)
.setSound(alarmSound)
.setStyle(bigPictureStyle)
.setSmallIcon(R.drawable.getspot_logo)
.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
.setContentText(message)
.build();
NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(Config.NOTIFICATION_ID_BIG_IMAGE, notification);
}
/**
* Downloading push notification image before displaying it in
* the notification tray
*/
public Bitmap getBitmapFromURL(String strURL) {
try {
URL url = new URL(strURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
// Playing notification sound
public void playNotificationSound() {
try {
Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
+ "://" + mContext.getPackageName() + "/raw/notification");
Ringtone r = RingtoneManager.getRingtone(mContext, alarmSound);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Method checks if the app is in background or not
*/
public static boolean isAppIsInBackground(Context context) {
boolean isInBackground = true;
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
for (String activeProcess : processInfo.pkgList) {
if (activeProcess.equals(context.getPackageName())) {
isInBackground = false;
}
}
}
}
} else {
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;
if (componentInfo.getPackageName().equals(context.getPackageName())) {
isInBackground = false;
}
}
return isInBackground;
}
// Clears notification tray messages
public static void clearNotifications(Context context) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
notificationManager.cancelAll();
}
public static long getTimeMilliSec(String timeStamp) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date = format.parse(timeStamp);
return date.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}
}
注意:我想向用户显示所有通知,当他们单击通知时,它应该显示,否则我想显示所有通知。请帮助我。基于通知,只有清除旧通知,用户才需要执行任务意味着,用户不知道以前发出了什么通知。
答案 0 :(得分:0)
您应为每个通知使用不同的notifyId,以将其单独显示。 Add a new notification when push notification receives (not replace old one)
在这里已经有答案在发布新问题之前,请先搜索SO。
答案 1 :(得分:0)
您具有通知int notifyID = 1所使用的硬编码ID; 因此,每次收到通知时,都会将相同的值(1)传递给方法
mNotificationManager.notify(notifyID , notification);
使其覆盖上一个,确保每次显示通知时都传递唯一的“ notifyID”,例如,我建议将int notifyID设置为静态并在将通知增量值显示为1以后,或者可以使用时间戳记(时间戳很长,因此将其类型转换为int),然后传入方法。
希望这会有所帮助,
快乐的编码...:)