Android: Manage multiple push notification in device of an app - android

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);

Related

GCM message is getting overridden

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());

Add a new notification when push notification is received (not replace the previous)

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);

How to open same activity after clicked difference notifications

i spend a lot of time to resolve my problem. i have written a messenger client in android. my application receive income message and raise a notification. in notification bar i display each income message in a notification item. when click to notification item it will open a conversation activity to list all messages from the beginning until now. everything dose perfect but when i click another item in notification bar, nothing happen! (it must reload data for another conversation). This is my code to raise a notification:
private void showNotification(String message, Class activity, Message messageObject) {
//Get the Notification Service
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence text = message;//getText(R.string.service_started);
Notification notification = new Notification(R.drawable.ic_launcher, text, System.currentTimeMillis());
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Intent callbackIntent = new Intent(context, activity);
if(messageObject != null)
{
callbackIntent.putExtra("conversation", MessageManager.getProvider().getConversation(messageObject.getConversationId()));
}
//callbackIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
int myUniqueValue = new Random().nextInt();
PendingIntent contentIntent = PendingIntent.getActivity(context, myUniqueValue, callbackIntent, PendingIntent.FLAG_ONE_SHOT);
notification.setLatestEventInfo(context, messageObject.getFrom(), text, contentIntent);
notificationManager.notify(messageObject.getFrom(), myUniqueValue, notification);
}
This is code block to call showNotification function
showNotification(message.getBody(), ConversationActivity.class, messageObject);
Despite your efforts to supply a unique value, those PendingIntents are all treated as the same by the system, so once you click one, the rest are rendered inert.
You'll need to add something distinguishing to callbackIntent; I suggest inventing a data URI that includes the conversation ID or something else that's guaranteed to be different for each notification (see setData).
Finally, I'd encourage you to try to collapse multiple notifications into one icon—you don't want to spam the user. See the Notifications section in the Android Design guide, under "Stack your notifications".
i changed my code and it work very well
private void showNotification(Context context, CharSequence contentTitle, CharSequence contentText, CharSequence notificationContent, Class activity, Conversation conversation) {
//Get the Notification Service
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher, notificationContent, System.currentTimeMillis());
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Intent callbackIntent = new Intent(context, activity);
if(conversation != null)
{
callbackIntent.putExtra("conversation", conversation);
}
callbackIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
int myUniqueValue = new Random().nextInt();
PendingIntent contentIntent = PendingIntent.getActivity(context, myUniqueValue, callbackIntent, PendingIntent.FLAG_ONE_SHOT);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
notificationManager.notify(myUniqueValue, notification);
}

Android Show Notification only when Message arrives

In Android, I have implemented Google Cloud Notification, which notifies when any message arrives, but it stays even when message is there, it shows icon in notification bar immediatly after installing application, is there any way to only show the notification when message arrives and hide it once the user clicks on it ??
Here is my code :
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, MainActivity.class); //Open Activity
// set intent so it does not start a new activity
Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
notificationIntent.setData(Uri.parse("http://www.google.com")); //Open Link
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;
//notification.sound = Uri.parse("android.resource://" + context.getPackageName() + "your_sound_file_name.mp3");
// Vibrate if vibrate is enabled
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, notification);
}
Without seeing where you are receiving messages and where you want to generate and cancel Notifications, it is very difficult to discern what you need to do to implement this, but I will give it a shot.
If you load the sample project for an Android Connected App Engine project (via GCM), you will notice that GCM data is received in a GCMBaseIntentService.
This class has a method you can override called onMessage() that will be called whenever you receive a GCM message. If you create the notification in this method, then your application will only generate a notification when a GCM message is received.
As for cancelling notifications- you can do so by calling the NotificationManager's cancel() method, passing the ID of the notification you want to cancel. Presumably you have some sort of Activity that displays messages to the user, and this would be a good place to cancel any outstanding Notifications relating to a specific message.

android GCM push notifications

I have successfully set up the code to run GCM over phonegap on an android app. I have managed to secure the handset registration ID and able to send a message to the app using this ID in a PHP script.
My only problem is that the message displays as a javascript alert whilst the app is open, and I am looking to have message sent to the handset's but not showing icon on top notifications bar .
**> does is possible showing icon on top bar in android device
Does anyone know if the GCM plugin for Phonegap is capable of doing this?**
I have using C2DM-Phonegap.
https://github.com/marknutter/GCM-Cordova
please help me friends...
The library you are using specifies what needs to be done when a message is received. You can either modify their code to do what you want or roll your own GCMIntentService.
please refer this links :
https://github.com/phonegap-build/PushPlugin
https://build.phonegap.com/plugins/324
The library you are using specifies what needs to be done when a message is received. You can either modify their code to do what you want or roll your own GCMIntentService.
The quickest way is to add the following code to GCMIntentService.java into the onMessage function. The GCM plugin you are using only receives the GCM message, but you have to trigger notifications on your own. You can also try a cordova plugin for status bar notifications.
protected void onMessage(Context context, Intent intent) {
Log.d(TAG, "onMessage - context: " + context);
// Extract the payload from the message
Bundle extras = intent.getExtras();
if (extras != null) {
String message = extras.getString("message");
String title = extras.getString("title");
Notification notif = new Notification(R.drawable.ic_launcher, message, System.currentTimeMillis() );
notif.flags = Notification.FLAG_AUTO_CANCEL;
notif.defaults |= Notification.DEFAULT_SOUND;
notif.defaults |= Notification.DEFAULT_VIBRATE;
Intent notificationIntent = new Intent(context, SomeActivity.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notif.setLatestEventInfo(context, "Title of notification", message, contentIntent);
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(ns);
mNotificationManager.notify(1, notif);
please check this code
private static void generateNotification(Context context, String message) {
int icon = R.drawable.ic_launcher;
// here is your icon drawable instead of 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.getApplicationContext(), devicephp.class);
// set intent so it does not start a new activity
notificationIntent.putExtra("msg", message);
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;
notificationManager.notify(0, notification);
}

Categories

Resources