Update android notification adding new message to old message - android

My app sends notifications but the problem is that if there are some notification pending in the action bar, I want to update the message adding the new message to the old message.
For example, if the message is Hi!, and the device receive another message (Pamela) before the user has opened the old message, I want to show only one notification with the message Hi! Pamela.
My code for send notifications is:
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, msg, when);
String title = this.getString(R.string.app_name);
Intent notificationIntent = new Intent(getApplicationContext(),
FirstActivity.class);
notificationIntent.putExtra("message", msg);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
int notifyID = 1;
PendingIntent intent = PendingIntent.getActivity(this, notifyID,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setLatestEventInfo(this, title, msg, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
Is it possible to get the old message of PendingIntent?
Thanks in advance.

One way to do this is to concatenate the string, by saving what is already displayed like, before the following is called for the first time:
notificationIntent.putExtra("message", msg);
//save "Hi" , concat "Pamela" update the notification with the same notification id
You save the string msg, then concatenate the string that you receive in the next notification. However, to identify, which notifications contain parts of String to be concatenated, is required in this case. Either you can set prefixes to messages or identify by notification id.
Not the ideal way to do it i feel, but can't think of anything else.

It's not possible to retrieve the existing notification from the NotificationManager. You need to keep track of it yourself independently of the notification, and save the unread messages somewhere else (maybe in a SQLite Database or SharedPreferences file).
You will need to determine if the user swipes away the notification, which means you will have to use the NotificationCompat.Builder class to create the notification. You can use the setDeleteIntent method to supply an Intent to trigger when the notification is swiped away, at which point you delete the old messages from wherever you are storing them so that a new message will show a notification with only the new message.

Related

Get unseen android notifications

I have a service that shows a notification PendingIntent each time it receives a new GCM message. The problem is that the GCM messages can be of different kinds. And if many notifications leave unread, I want not to show them separately but in groups like:
you have 3 unread messages of type A
you have 2 unread messages of type B
you have 4 unread messages of type C
As far as I understand, to get this effect I need to have an access to unread/unseen notifications. Each time when I new notification comes I can check, if there is another unread message of this type, and then decide, whether I create a new notification or update an old one.
My question is: is there a way to see, which notifications are unseen and get access to them?
For any case this is my method to create a message; if an argument notificationId is 0 a new notification should be created. Else - updated.
private int sendNotification(String msg, Integer notificationId) {
Log.d(TAG, "sending message with text: "+msg);
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
Random random = new Random();
int notification_id = notificationId==0?random.nextInt(9999 - 1000) + 1000:notificationId;
RemoteViews remoteViews = new RemoteViews(getPackageName(),
R.layout.notification);
Intent intent = new Intent(this, MainActivity.class);
// Send data to NotificationView Class
intent.putExtra("text", msg);
PendingIntent pending= PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("escos")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(pending);
mBuilder.setContent(remoteViews);
remoteViews.setTextViewText(R.id.notiftext, msg);
remoteViews.setImageViewResource(R.id.notifim, R.drawable.ic_launcher);
Notification notification = mBuilder.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mNotificationManager.notify(notification_id, notification);
return notification_id;
}
For different Notification strip (A, B, C etc.) in your status bar, use different NOTIFICATION_ID for building the Notification on basis of your defined type or collapse_key received from GCM.
For determining unread and read messages, use a local variable (counter) in Shared Preferences and increment it each time a specific type of Notification comes (on basis of defined type or collapse_key).
Then generate the Notification with that particular NOTIFICATION_ID as Notification with particular NOTIFICATION_ID can override each other. So You can override the previous Notification with Iterative Numbered text in New Notification.
As soon as user click on any Notification or particular Notification, clear the notification and reset the value of (counter) in Shared Preferences.
Edit1 : When you click on Notification with particular Pending Intent, then in that Activity use this code for removing all the Notifications generated from your app :
NotificationManager nMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
try {
nMgr.cancelAll();
} catch (Exception e) {
e.printStackTrace();
}
Note : Do remember to add Try-Catch before you call cancelAll() as cancelAll() may not be supported by the device model and will generate
java.lang.SecurityException: Permission Denial
error.
Edit 2:
You can also use nMgr.cancel(NOTIFICATION_ID); to clear a specific notification, pass NOTIFICATION_ID to particular intent via extras and get the extras in that activity to cancel a particular notification.
And as you click on any notification it will be cleared from status bar unless you have not set .setAutoCancel(false) in your Notification Builder.

To generate push notification based on user current device location in android

I am able to get push notification from server but my app should receive push notification when user device location change in latitude and longitude.
Case 1:
I have to send device latitude and longitude values to server and it has to send push notification whenever user device current location change.(Moves from Place A to Place B to get notification) even if the app is running in background,app needs to configure with system OS to get push.
Case 2:
Iam able to move to activity while clicking on push notification but i need like if i have received two push notification from server clicking on first notification it has to take FirstActivity and clicking on second push notification take to secondActivity.
How to identify which push notification is to redirect to activity.
code to show push notification in GCMNotificationIntentService:
private void createNotification(String msg){
Log.d(TAG, "Preparing to send notification...: " + msg);
NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.offer, "GCM Notification", System.currentTimeMillis());
Intent notificationIntent = new Intent(this, FirstActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(this, NOTIFICATION_ID,notificationIntent, 0);
notification.setLatestEventInfo(this, "Message From GCM", msg, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(NOTIFICATION_ID, notification);
NOTIFICATION_ID = NOTIFICATION_ID + 1;
}
1.You need to create service which will be runing in background. Also you need somehow send notification to the telephone from your server and handle it. But it could be achived without server, you could just listen to LocationListener.OnLocationChanged
2.According to second question you can prepare right Intent before displaying notification, assign it to the notification, and after clicking it, you will be moved directly to this activity.
Intent intent = //prepare your intent
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this).setContentIntent(contentIntent);
notificationManager.notify(notificationId, builder.build());

Why is multiple notifications not displayed simultaneously?

I have included a unique id for creating PendingIntent as well as in mNM.notify() method. When I set two notifications to display at the same time they do not get displayed simultaneously. The first notification get displayed with the time given for the second notification. Many people have had this problem and the only suggestion was to give unique IDs. But that doesn't work! Please Help. Below is my showNotification() method.
private void showNotification() {
/*create intent for show notification details when user clicks notification*/
Intent intent =new Intent(getApplicationContext(), MainActivity.class);
Random random = new Random();
int id = random.nextInt();
intent.setData((Uri.parse("custom://"+System.currentTimeMillis())));
// This is the 'title' of the notification
CharSequence title = "Reminder!" + id;
// This is the icon to use on the notification
int icon = R.drawable.ic_dialog_alert;
// This is the scrolling text of the notification
CharSequence text = task;
// What time to show on the notification
long time = System.currentTimeMillis();
Notification notification = new Notification(icon, text, time);
// The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent = PendingIntent.getActivity(this,id, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
// Set the info for the views that show in the notification panel.
notification.setLatestEventInfo(this, title, text, contentIntent);
// Clear the notification when it is pressed
notification.flags |= Notification.FLAG_AUTO_CANCEL;
// Send the notification to the system.
mNM.notify((int)System.currentTimeMillis(), notification);
// Stop the service when we are finished
stopSelf();
}
I haven't tried this unsupported answer.
I think your looking for the .setOngoing(true)
The user can't cancel this notification so I imagine the OS can't cancel it either.

Single Notification but should deliver multiple pending intents when app is launched - Android

I am receiving multiple messages from GCM. When the app is running foreground or background i have no issues because i use broadcast receiver. But when the app is not running I would want to Queue the messages in the pendingIntent and keep it as part of the notification managers notification. So that when user clicks on the notification the mainActivity is launched and it is passed all the messages. I have posted the code below.
With current Code I am able to receive, only 1 message and that is the latest message, in the onCreate method of the activity.
To summarize the requirement
Application is not running. App Exited.
Call notify with pendingIntents on every new message received with Extra Field set to the message
Just one notification message in notification bar ( let us assume "number of messages received 3" is seen in notification bar)
Now User clicks the notification
Application should be able to read all the 3 messages by accessing the pendingIntent
Hope i can find help!
// build intent
final Intent notificationIntent = new Intent(context,
MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
notificationIntent.putExtra(CommonUtilities.EXTRA_MESSAGE, message);
notificationIntent.setAction("DUMMY");
// pending intent creation
int requestID = (int) System.currentTimeMillis();
// set intent so it does not start a new activity
final PendingIntent intent = PendingIntent.getActivity(context, requestID ,
notificationIntent, 0);
// create notification using intent
final String title = context.getString(R.string.app_name);
Notification notification = new NotificationCompat.Builder(context)
.setContentTitle(title)
.setContentText(formattedMessage)
.setSmallIcon(icon)
.setDefaults(Notification.FLAG_AUTO_CANCEL|Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
.setContentIntent(intent).build();
final NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, notification);
//Now in mainActivity:OnCreate
//Receive
Bundle extras = getIntent().getExtras();
if (extras != null) {
String inp = extras.getString(CommonUtilities.EXTRA_MESSAGE);
if (inp != null ) {
doSomething(inp);
}
}
Since you are the one receiving the GCM incoming messages, and you are the one raising the Notification, it is up to you to arrange to store the details of the GCM messages in a file or database, and it is up to you to arrange to show all those details when the user taps on the Notification.
Guys finally i used the following logic to solve my problem
Have a local array when receiving Intents.
If pending Intent Already Exists ( FLAG_NO_CREATE )
then
append the array with the new message and update the pending Intent
This way the EXTRA will have old + new message in an array
else
Clear the old message array because the notification has already been cleared.
Now add the new EXTRA with ( FLAG_UPDATE CURRENT)
End
Then Notify
Now when user clicks on the single notification a new activity is launched.
In MainActivity Oncreate I read the intent data and go in a loop and all the messages that I would have missed when the app was not running!
Ofcourse not aware of how heavy it would be on the notification bar if the user does not click on the notification for a long time!

Send multiple notifications androidle

I am trying to recieve multiple notifications on my mobile.But each time i send the notification.The previous notification gets overwritten by the new one.I watched the other questions where they said to have multiple Id's for notifications I am doing that also but I don't know where I am going wrong.
Here's how I create my notification.(It is being created in a service).
private void GenerateNotification(String data)
{
String ns=Context.NOTIFICATION_SERVICE;
manager=(NotificationManager) getSystemService(ns);
int icon=R.drawable.ic_launcher;
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, data, when);
notification.flags |=Notification.FLAG_AUTO_CANCEL;
notification.defaults |= Notification.DEFAULT_SOUND;
Context context = getApplicationContext();
CharSequence contentTitle = "The Best Essay";
CharSequence contentText = data;
Intent notificationIntent = new Intent(this,MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
manager.notify(HELLO_ID, notification);
HELLO_ID++;
}
Where HelloID increments to recieve multiple notifications with unique id's.Please tell me where I am doing wrong.
So the issue is that the intent you're using is the same each time. If you try to notify the user using an Intent that is the same as one used in a notification that is already being displayed, android considers them duplicates. This is because each notification when clicked will end up doing the exact same thing (so android is like "why do I need to display two of these?").
The thing to do is say "hey, am I already displaying a notification? If so, I'm going to create a new notification that will override the current one, but convey the fact that there are actually two things that I'm notifying about". Consider the text messaging application. When you get a second unread text message, it overrides the first notification about the original text message and replaces it with a notification tell you that you have two new text messages. Make sense?

Categories

Resources