Как отображать несколько уведомлений в android
Я получаю только одно уведомление, и если есть другое уведомление, оно заменяет предыдущее, и вот мой код
private static void generateNotification(Context context, String message,
String key) {
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
String title = context.getString(R.string.app_name);
Intent notificationIntent = new Intent(context,
FragmentOpenActivity.class);
notificationIntent.putExtra(key, key);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.defaults |= Notification.DEFAULT_SOUND;
// notification.sound = Uri.parse("android.resource://" +
// context.getPackageName() + "your_sound_file_name.mp3");
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, notification);
}
Ответы
Ответ 1
Я решил свою проблему следующим образом:
/**
* Issues a notification to inform the user that server has sent a message.
*/
private static void generateNotification(Context context, String message,
String keys, String msgId, String branchId) {
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
NotificationCompat.Builder nBuilder;
Uri alarmSound = RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
nBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Smart Share - " + keys)
.setLights(Color.BLUE, 500, 500).setContentText(message)
.setAutoCancel(true).setTicker("Notification from smartshare")
.setVibrate(new long[] { 100, 250, 100, 250, 100, 250 })
.setSound(alarmSound);
String consumerid = null;
Integer position = null;
Intent resultIntent = null;
if (consumerid != null) {
if (msgId != null && !msgId.equalsIgnoreCase("")) {
if (key != null && key.equalsIgnoreCase("Yo! Matter")) {
ViewYoDataBase db_yo = new ViewYoDataBase(context);
position = db_yo.getPosition(msgId);
if (position != null) {
resultIntent = new Intent(context,
YoDetailActivity.class);
resultIntent.putExtra("id", Integer.parseInt(msgId));
resultIntent.putExtra("position", position);
resultIntent.putExtra("notRefresh", "notRefresh");
} else {
resultIntent = new Intent(context,
FragmentChangeActivity.class);
resultIntent.putExtra(key, key);
}
} else if (key != null && key.equalsIgnoreCase("Message")) {
resultIntent = new Intent(context,
FragmentChangeActivity.class);
resultIntent.putExtra(key, key);
}.
.
.
.
.
.
} else {
resultIntent = new Intent(context, FragmentChangeActivity.class);
resultIntent.putExtra(key, key);
}
} else {
resultIntent = new Intent(context, MainLoginSignUpActivity.class);
}
PendingIntent resultPendingIntent = PendingIntent.getActivity(context,
notify_no, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
if (notify_no < 9) {
notify_no = notify_no + 1;
} else {
notify_no = 0;
}
nBuilder.setContentIntent(resultPendingIntent);
NotificationManager nNotifyMgr = (NotificationManager) context
.getSystemService(context.NOTIFICATION_SERVICE);
nNotifyMgr.notify(notify_no + 2, nBuilder.build());
}
Ответ 2
просто замените вашу строку на
notificationManager.notify(Unique_Integer_Number, notification);
надеюсь, что это вам поможет.
Ответ 3
Простая идентификация уведомления должна быть изменчивой.
Просто создайте случайное число для notification_id.
Random random = new Random();
int m = random.nextInt(9999 - 1000) + 1000;
или вы можете использовать этот метод для создания случайного числа, как указано tieorange (это никогда не будет повторяться):
int m = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);
и замените эту строку, чтобы добавить параметр для идентификатора уведомления, чтобы генерировать случайное число
notificationManager.notify(m, notification);
Ответ 4
Использование общих настроек работало для меня
SharedPreferences prefs = getSharedPreferences(Activity.class.getSimpleName(), Context.MODE_PRIVATE);
int notificationNumber = prefs.getInt("notificationNumber", 0);
...
notificationManager.notify(notificationNumber , notification);
SharedPreferences.Editor editor = prefs.edit();
notificationNumber++;
editor.putInt("notificationNumber", notificationNumber);
editor.commit();
Ответ 5
Я думаю, это поможет кому-то..
в нижеприведенном коде "not_nu" является случайным int.. PendingIntent и Notification имеют одинаковый идентификатор.. так что при каждом уведомлении нажмите намерение будет направлено на различную активность.
private void sendNotification(String message,String title,JSONObject extras) throws JSONException {
String id = extras.getString("actionParam");
Log.e("gcm","id = "+id);
Intent intent = new Intent(this, OrderDetailActivty.class);
intent.putExtra("id", id);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
final int not_nu=generateRandom();
PendingIntent pendingIntent = PendingIntent.getActivity(this, not_nu /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_cart_red)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(not_nu /* ID of notification */, notificationBuilder.build());
}
public int generateRandom(){
Random random = new Random();
return random.nextInt(9999 - 1000) + 1000;
}
Ответ 6
Замените свою строку на это.
notificationManager.notify((int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE), notification);
Ответ 7
В месте uniqueIntNo
поместите уникальное целое число, подобное этому:
mNotificationManager.notify(uniqueIntNo, builder.build());
Ответ 8
Вам нужно добавить уникальный идентификатор к каждому из уведомлений, чтобы они не сочетались друг с другом. Вы можете использовать эту ссылку для справки:
https://github.com/sanathe06/AndroidGuide/tree/master/ExampleCompatNotificationBuilder
Ответ 9
Другой способ сделать это - взять текущую дату, преобразовать ее в длинный, просто взять последние 4 цифры. Существует высокая вероятность того, что число будет уникальным.
long time = new Date().getTime();
String tmpStr = String.valueOf(time);
String last4Str = tmpStr.substring(tmpStr.length() -5);
int notificationId = Integer.valueOf(last4Str);
Ответ 10
Проблема с вашим notificationId
. Подумайте, что это индекс массива. Каждый раз, когда вы обновляете уведомление, notificationId
- это место, которое требуется для сохранения значения. Поскольку вы не увеличиваете значение int (в данном случае, ваш notificationId
), это всегда заменяет предыдущее. Лучшее решение, я думаю, заключается в том, чтобы увеличить его сразу после обновления уведомления. И если вы хотите сохранить его постоянным, вы можете сохранить значение notificationId
в sharedPreferences
. Когда вы вернетесь, вы можете просто взять последнее целочисленное значение (notificationId
, сохраненное в sharedPreferences
) и использовать его.
Ответ 11
Ниже приведен код для идентификатора уникального идентификатора прохода:
//"CommonUtilities.getValudeFromOreference" is the method created by me to get value from savedPreferences.
String notificationId = CommonUtilities.getValueFromPreference(context, Global.NOTIFICATION_ID, "0");
int notificationIdinInt = Integer.parseInt(notificationId);
notificationManager.notify(notificationIdinInt, notification);
// will increment notification id for uniqueness
notificationIdinInt = notificationIdinInt + 1;
CommonUtilities.saveValueToPreference(context, Global.NOTIFICATION_ID, notificationIdinInt + "");
//Above "CommonUtilities.saveValueToPreference" is the method created by me to save new value in savePreferences.
Reset notificationId в savedPreferences в определенном диапазоне, например, я сделал это на 1000. Поэтому он не будет создавать никаких проблем в будущем.
Дайте мне знать, если вам нужна более подробная информация или любой запрос.:)
Ответ 12
Используйте следующий метод в коде.
Вызов метода: -
notificationManager.notify(getCurrentNotificationId(getApplicationContext()), notification);
Метод: -
*Returns a unique notification id.
*/
public static int getCurrentNotificationId(Context iContext){
NOTIFICATION_ID_UPPER_LIMIT = 30000; // Arbitrary number.
NOTIFICATION_ID_LOWER_LIMIT = 0;
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(iContext);
int previousTokenId = sharedPreferences.getInt("currentNotificationTokenId", 0);
int currentTokenId = previousTokenId+1;
SharedPreferences.Editor editor = sharedPreferences.edit();
if(currentTokenId<NOTIFICATION_ID_UPPER_LIMIT) {
editor.putInt("currentNotificationTokenId", currentTokenId); // }
}else{
//If reaches the limit reset to lower limit..
editor.putInt("currentNotificationTokenId", NOTIFICATION_ID_LOWER_LIMIT);
}
editor.commit();
return currentTokenId;
}
Ответ 13
notificationManager.notify(0, notification);
putthis new Random().nextInt() in position of 0
like below it works for me
notificationManager.notify(new Random().nextInt(), notification);
Ответ 14
Вам просто нужно поменять свою однострочную строку по notificationManager.notify(0, notification);
notificationManager.notify((int) System.currentTimeMillis(), notification);
...
Это изменит идентификатор уведомления всякий раз, когда появится новое уведомление
Ответ 15
Простой счетчик может решить вашу проблему.
private Integer notificationId = 0;
private Integer incrementNotificationId() {
return notificationId++;
}
NotificationManager.notify(incrementNotificationId, notification);
Ответ 16
declare class member
static int i = 0;
mNotificationManager.notify(++i, mBuilder.build());
Ответ 17
val notifyIdLong = ((Date().time / 1000L) % Integer.MAX_VALUE)
var notifyIdInteger = notifyIdLong.toInt()
if (notifyIdInteger < 0) notifyIdInteger = -1 * notifyIdInteger // if it -ve change to positive
notificationManager.notify(notifyIdInteger, mBuilder.build())
log.d(TAG,"notifyId = $notifyIdInteger")