I am using GCM push notification to pass some notification to the user. My problem is when am sending single message then this works fine if send more than one then the last message is shown to all the notification.
Where have I made a mistake?
private static void generateNotification(Context context, String message) {
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, GCMMessageView.class);
String[] messageArray = message.split("\\#");
// param :: agentId, Name, Msg
DatabaseHelper db = new DatabaseHelper(context);
int notificationId = db.insertnotifications(messageArray[1], messageArray[0], messageArray[messageArray.length-1]);
notificationIntent.putExtra("message", messageArray[messageArray.length-1]);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(context)
.setContentText(messageArray[messageArray.length-1])
.setContentTitle(context.getString(R.string.app_name))
.setSmallIcon(icon)
.setWhen(when)
.setContentIntent(intent)
.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
// Play default notification sound
notification.defaults |= Notification.DEFAULT_SOUND;
// Vibrate if vibrate is enabled
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(notificationId, notification);
}
used this coding in your notification
int requestID = (int) System.currentTimeMillis();
PendingIntent intent = PendingIntent.getActivity(context, requestID,
notificationIntent,0 );
then your notification will not override i hope this will help u
Make notification id unique for each message. Due to this, it's being overridden.
Yes agree with Dipo's answer. According to Android Notification Developer Guide This is being overridden due to same notification id for more than one notification.SO the last message is being received on receiver end. You need to Implement random unique Notification id for each notifications. There are number of ways to implement this . You can use this
int notificationId = new Random().nextInt();
You can also use system time in Mili Seconds for Notification id.Then you need to pass this unique Notification ID to notificationManager.notify()
Cheers ! Keep Coding
Quite late to answer for the thread but felt it will be helpful for someone. The same implementation works fine for FCM firebase implementation as well
// Get a random value
int notificationId = new Random().nextInt();
// Add the notification ID which is unique as a first value of the notify method.
notificationManager.notify(notificationId, notificationBuilder.build());
Related
I submitted my app at the end of 2017 in the play store and it worked.
Then it was built in Eclipse.
Now I run it in Android Studio and the same code doesn't show any notification.
It is a permanent notification which is present after I call the app's finish() method. (why I do this: see at the bottom if you want to know).
So I looked at all the examples and NONE of the work. No single notification is shown.
So I start an activity and in the activity I show the notification. Then I call finish().
This is my code:
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
intent, 0);
CharSequence connectedPart = getResources().getString(R.string.app_name);
String melding = "";
melding = getResources().getString(R.string.screentimeoutsetto) + " " + newTimeString + ".";
NotificationManager notificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification.Builder(this)
.setContentTitle(connectedPart)
.setTicker(connectedPart)
.setContentText(melding)
.setSmallIcon(R.drawable.ic_stat_name)
.setContentIntent(pendingIntent)
.setOngoing(true)
.build();
notification.flags |= Notification.FLAG_ONGOING_EVENT;
notification.flags |= Notification.FLAG_NO_CLEAR;
notificationManager.notify(2, notification);
dependencies:
dependencies{
implementation "com.android.support:support-compat:26.1.0"
}
Why I do this:
My app does 1 thing: toggle the screentimeout. So when you start it it sets the screentimeout to 30 minutes (starts, sets a notification, then finish()). Start again, it removes the notification and restore the original value for the screen timeout.
Starting with Android Oreo, all notifications require a notification channel, otherwise the notification wont post and an error will appear in your logcat. Here's an example of how you can do it, lifted from one of my apps:
private static void createNotificationChannel(Context ctx) {
if(SDK_INT < O) return;
final NotificationManager mgr = ctx.getSystemService(NotificationManager.class);
if(mgr == null) return;
final String name = ctx.getString(R.string.channel_name);
if(mgr.getNotificationChannel(name) == null) {
final NotificationChannel channel =
new NotificationChannel(CHANNEL_ID, name, IMPORTANCE_DEFAULT);
mgr.createNotificationChannel(channel);
}
}
//Usage...
createNotificationChannel(context);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID);
builder.setSmallIcon(R.drawable.ic_alarm_white_24dp);
//etc...
manager.notify(id, builder.build());
Now from Android 8.0 and onward you need to create notification channel before showing notifications. Here is the Docs link
https://developer.android.com/training/notify-user/channels
Whenever I receive a push notification on Android it replaces any existing notification in the drawer.
any idea to fix that?
Below is my code:
NotificationManager notificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
Intent intent = new Intent(DbInsertService.this, MessageActivity.class);
intent.putExtra("Service",serviceType);
PendingIntent pIntent = PendingIntent.getActivity(DbInsertService.this, (int)
System.currentTimeMillis(), intent,PendingIntent.FLAG_UPDATE_CURRENT);
Notification n = new Notification.Builder(DbInsertService.this)
.setContentTitle("Message from " +serviceType.getSer_name())
.setContentText(messageType.getHis_title())
.setSmallIcon(R.drawable.ic_email_variant_grey600_24dp)
.setContentIntent(pIntent)
.setAutoCancel(true).build();
notificationManager.notify(0, n);
thanks
Set different Id for different notification.
notificationManager.notify(0, n); // here set different Id.
You're sending them all with the same id. Send different ids and they won't overwrite.
My app generates notifications like so :
final Bundle intentExtras = intent.getExtras();
final String title = intentExtras.getString(Constants.EXTRA_TITLE);
final String body = intentExtras.getString(Constants.EXTRA_BODY);
final Integer notifID = intentExtras.getInt(Constants.EXTRA_ID);
// this pending intent will launch after notification is selected
Intent notificationIntent = new Intent(context, NotificationReceiverActivity.class);
notificationIntent.putExtras(intentExtras);// pass the extra data forward to NotificationReceiverActivity
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(context, notifID, notificationIntent, PendingIntent.FLAG_ONE_SHOT);
// build notification to show on the notification bar
try
{
final String packagename = context.getPackageName();
PackageInfo packageinfo = context.getApplicationContext().getPackageManager().getPackageInfo(packagename, 0);
final int iconid = packageinfo.applicationInfo.icon;
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setAutoCancel(false)
.setContentIntent(pendingIntent)
.setSmallIcon(iconid)
.setContentTitle(title)
.setContentText(body);
// build notification and set alerts
Notification notification = mBuilder.build();
notification.defaults |= Notification.DEFAULT_ALL;
// show notification
NotificationManager notificationMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationMgr.notify(notifID, notification);
}
catch (android.content.pm.PackageManager.NameNotFoundException e)
{}
each notifID is unique ! However, if the app is showing two or more notifications, and the user selects one of them, both notifications for the app are cleared !
I have tried using setAutoCancel(false) or setAutoCancel(true) but it doesn't make a difference.
Additionally, there are no calls to NotificationManager.cancel() or NotificationManager.cancelAll()
How can I prevent the app from clearing all notifications for the app after a user has selected just one of them ?
FURTHER INVESTIGATION...
I've found that the notifications for the app disappear after I launch the app.
However, no .cancel() or .cancelAll() in sight... /confused
Answer: Crosswalk (XWalkView) took the liberty of .cancelAll() notifications !!!
/facepalm x 100000
https://github.com/wuhengzhi/crosswalk/commit/32205e256dbb35ee70c895de4fe7c76d165b30dd
I am developing an application in which i implemented Push notification functionality.
My code of onMessage - GCMIntentService.java is:
#Override
protected void onMessage(Context context, Intent data) {
String message = data.getExtras().getString("message");
displayMessage(context, message);
generateNotification(context, message);
}
And code of generateNotification -
private static void generateNotification(Context context, String message) {
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, GCMMessageView.class);
notificationIntent.putExtra("message", message);
// 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;
// Play default notification sound
notification.defaults |= Notification.DEFAULT_SOUND;
// Vibrate if vibrate is enabled
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, notification);
}
This code is working fine. I am getting push message and notification.
=>But when i send more then one message the notification gets over write. And i am able to see only last notification in status bar.
The need of application is that - if i send more then one notification then all should be display in status bar.
So please guide me what should i do for that in my code.
Try to put different notification id (i.e. nid) in intent and notify instead of 0 for each new notification this will prevent over writing your notification
PendingIntent intent = PendingIntent.getActivity(context, nid,notificationIntent, 0);
and
notificationManager.notify(nid, notification);
Hope this will help you
Get random numbers:
Random random = new Random();
int m = random.nextInt(9999 - 1000) + 1000;
Instead of:
notificationManager.notify(0, notification);
use:
notificationManager.notify(m, notification);
You need to update your Notification ID when you fire a Notification. in
notificationManager.notify(ID, notification);
How?
To set up a notification so it can be different, issue it with a notification ID by calling NotificationManager.notify(ID, notification). To change this notification once you've issued it, create a NotificationCompat.Builder object, build a Notification object from it, and issue the Notification with the Different ID you are not used previously.
If the previous notification is still visible, the system updates it from the contents of the Notification object. If the previous notification has been dismissed, a new notification is created instead.
For more information go to official docs
hello you need to pass unique notification id in notify method.
Below is the code for pass unique notification id:
//"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.
Let me know if you need more detail information or any query. :)
notificationManager.notify(Different_id_everytime, notification);
I am using push notifications in my app. I need to display a notification when a push notification delivered. If I send another notification (without clearing the previous notification), it will replace the old notification.
This is the code I use:
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int icon = R.drawable.ic_launcher;
CharSequence tickerText = "New notification Pending";
long time = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, time);
notification.flags = Notification.DEFAULT_LIGHTS | Notification.FLAG_AUTO_CANCEL;
// Context context = getApplicationContext();
CharSequence contentTitle = "Notifications";
CharSequence contentText = newMessage;
Intent notificationIntent = new Intent(this, LoginActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText,
contentIntent);
mNotificationManager.notify(1, notification);
But I don't want to replace the notification, I want to add it as a new notification.
You can also use System.currentTimeMillis() to assign unique id to your notification.
int id = (int) System.currentTimeMillis();
mNotificationManager.notify(id, notification);
You need to supply a different ID as the notification ID each time. The best approach would be to send an ID field to GCM which can be then accessed via Intent.getExtras().getInt() in your GCMIntentService's onMessage() method.
If this is not possible, I'd suggest using something like (int)Math.random()*10 to generate a random integer number as your notification ID. This will (partially) ensure that your notifications will not replace each other.
simple you have to
change Notification id
mNotificationManager.notify(1, notification);
instead of 1
for more refer this Link
Use a new notification ID every time instead of hardcoding to 1:
int i = x; //Generate a new integer everytime
mNotificationManager.notify(i, notification);
I am not sure what your use case is, but the Android design guidelines recommend not doing it at all.
Don't:
Do:
We need Unique notification id which will generate the new notifications.
Post a notification to be shown in the status bar. If a notification with
the same id has already been posted by your application and has not yet been canceled, it will be replaced by the updated information.
#param id An identifier for this notification unique within your application.
#param notification A {#link Notification} object describing what to show the user.
Must not be null.
public void notify(int id, Notification notification)
{
notify(null, id, notification);
}
Example :
int id =(int) System.currentTimeMillis();
mNotificationManager.notify(id, notify);