Update notifcation text - android

I have currently setup a small application which sets an alarm on the device and stores relevant information inside of an SQL database e.g. Alarm name and time. When the alarm is activated my application sends a notification to the user. Currently each notification is static which means every message is the same. I would like to now allow my application to grab the name of the alarm which has been activated and display it in the notification. Now I know that when setting multiple alarms you require multiple ID's which I have stored in side of my SQL and I'm guess the same when it comes to sending a notification. Is there a way of matching my Alarms ID with one on a notification so that it knows what message to send e.g. alarm name?
Current code for setting my Alarm
pendingIntent = PendingIntent.getBroadcast(view.getContext(), Integer.valueOf(alarm_request_code), receiver, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, myCalendar.getTimeInMillis(), pendingIntent);
intentArrayList.add(pendingIntent);
My Broadcast receiver...
NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
Intent moveActivity = new Intent(context, AlarmActivity.class);
moveActivity.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, moveActivity, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setContentIntent(pendingIntent)
.setContentTitle("Standard text")
.setContentText("Standard text")
.setSmallIcon(R.mipmap.ic_launcher)
.setAutoCancel(true);
notificationManager.notify(0, builder.build());
}
//////////////
Update on my situation which is slowly driving me crazy
I can now set the text from my SQL to my notification but its only the first from my database each time. Now I've come up with two possible solutions which are only theory's.
Is there a way in which each time the database is called to the notification it will move onto the next result?
As I mentioned above I'm setting an alarm and when the alarm goes off it then calls the notification. Now In my pending intent for the alarm I'm giving it a id which you can see as alarm_request_code is there a way of giving it to my notification ID and then setting up a statement where if the notification ID is equal to or in the list of my alarm ID's stored on my SQL then it will search for the correct text to input.
MyDatabaseHandler myDatabaseHandler = new MyDatabaseHandler(context, null, null, 1);
Cursor cursor = myDatabaseHandler.getAllProducts();
// Information we are trying to acquire but can only get first result
String name = cursor.getString(cursor.getColumnIndexOrThrow("alarm_name"));
String date = cursor.getString(cursor.getColumnIndexOrThrow("alarm_date"));
// Alarm ID FROM SQL which we want to match with the NOTIFICATION ID.....
String alarm_request_code = cursor.getString(cursor.getColumnIndexOrThrow("alarm_code"));
////
Log.i("The reciever is working", "perfect");
//create an intent to service
Intent service_Intent = new Intent(context, MessageService.class);
context.startService(service_Intent);
//Notification
NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
Intent moveActivity = new Intent(context, AlarmActivity.class);
moveActivity.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Works with moveActivity to move the user back to main application.
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, moveActivity, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setContentIntent(pendingIntent)
.setContentTitle(name)
.setContentText(date)
.setSmallIcon(R.mipmap.ic_launcher)
.setAutoCancel(true);
notificationManager.notify(Integer.valueOf(alarm_request_code), builder.build());
}
}

To update text store mBuilder variable
and update later in this way:
mBuilder.setContentTitle(head);
mBuilder.setContentText(body);
mNotificationManager.notify(SIMPLE_ID, mBuilder.build());
EDIT
private void simple() {
Intent intent = new Intent(context, AlarmActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
mBuilder = new NotificationCompat.Builder(this);
mBuilder.setContentTitle(getResources().getString(R.string.app_name))
.setContentText(getResources().getString(R.string.app_name))
.setContentIntent(pIntent);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
mBuilder.setSmallIcon(R.drawable.ic_done_24dp);
} else {
mBuilder.setSmallIcon(someiconLollipop);
mBuilder.setColor(somecolorLollipop]);
}
noti = mBuilder.build();
//use flags if you need:
noti.flags = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;
mNotificationManager.notify(SIMPLE_ID, mBuilder.build());
}
to update the text:
private void showText() {
String head = yournewhead;
String body = yournewbody;
mBuilder.setContentTitle(head);
mBuilder.setContentText(body);
mNotificationManager.notify(SIMPLE_ID, mBuilder.build());
}

Per the docs you can do the following:
mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Sets an ID for the notification, so it can be updated
int notifyID = 1;
mNotifyBuilder = new NotificationCompat.Builder(this)
.setContentTitle("New Message")
.setContentText("You've received new messages.")
.setSmallIcon(R.drawable.ic_notify_status)
numMessages = 0;
// Start of a loop that processes data and then notifies the user
mNotifyBuilder.setContentText(currentText)
.setNumber(++numMessages);
// Because the ID remains unchanged, the existing notification is
// updated.
mNotificationManager.notify(
notifyID,
mNotifyBuilder.build());
The trick here is your notify id, which must be the same in order to behave appropriately, in your case 0.
So as long it has not been dismissed it should work accordingly. I will suggest having a unique id as a constant for your custom notification such as 123.
notificationManager.notify(0, builder.build());

Related

Not receiving notification of the next user

I have made a chat app in firebase and users are being notified when a new message comes by the below codes.
private void sendNotification(String title, String message, String receiver, String receiverUid, String firebaseToken) {
Intent intent = new Intent(this, ChatActivity.class);
intent.putExtra("name",title);
intent.putExtra(Const.ARG_RECEIVER, receiver);
intent.putExtra(Const.ARG_RECEIVER_UID, receiverUid);
intent.putExtra(Const.ARG_FIREBASE_TOKEN, firebaseToken);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
char[] ch = firebaseToken.substring(0,3).toCharArray();
String a = "";
for (char aCh : ch) {
a = a + Integer.toHexString(aCh);
}
PendingIntent pendingIntent = PendingIntent.getActivity(this, Integer.parseInt(a), intent,
PendingIntent.FLAG_ONE_SHOT);
// Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_noti)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
// .setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(Integer.parseInt(a), notificationBuilder.build());
}
I want to receive different notification when a different user sends a message but for the same user, the notification should be updated. I tried to set unique id by taking the Unicode of first 3 letters of Firebase token of the user but then also it is showing only one notification. If I chat with 2 people the user with whom I have started chat first shows notification but not the second one.
Please have a look and help. Thanks
Just change FLAG_ONE_SHOT to FLAG_UPDATE_CURRENT.
FLAG_ONE_SHOT :
Flag indicating that this PendingIntent can be used only once.
FLAG_UPDATE_CURRENT :
Flag indicating that if the described PendingIntent already exists, then keep it but replace its extra data with what is in this new Intent.

Notification code disappears automatically

When I receive the notification I would like it to automatically disappear and have to upload manually I, Thank you in advance.
Here I attach the code, in which I create the notification. What I want to happen is that when I receive the notification, I get off, I can see it on the screen, and after a few seconds I go up alone without having to interact with it.
public void notificacion(String label, String autor,String destino) {
NotificationCompat.Builder notifica = new
NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setLargeIcon((((BitmapDrawable) getResources()
.getDrawable(R.drawable.ic_launcher)).getBitmap()))
.setContentTitle("tittle")
.setContentText(label)
.setAutoCancel(true);
Intent intnot = new Intent(this, MainActivity.class);
intnot.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intnot.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intnot.putExtra("Destino", destino);
PendingIntent intnotpend = PendingIntent.getActivity(this, 0, intnot, PendingIntent.FLAG_UPDATE_CURRENT);
notifica.setContentIntent(intnotpend);
notifica.setFullScreenIntent(intnotpend, true);
notifica.setContentIntent(intnotpend);
}
NotificationManager notyman = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
notyman.notify(10, notifica.build());
}

Notification is not being dismissed (Android)

Notification setAutoCancel(true) doesn't work if clicking on Action
I have a notification with an action within it. When I tap on the notification it gets removed from the list. However, when I click on the Action it successfully completes the Action (namely makes a call), but when I return to the list of notifications, it remains there.
Relative code of the AlarmReceiver:
public class AlarmReceiver extends BroadcastReceiver {
Meeting meeting;
/**
* Handle received notifications about meetings that are going to start
*/
#Override
public void onReceive(Context context, Intent intent) {
// Get extras from the notification intent
Bundle extras = intent.getExtras();
this.meeting = extras.getParcelable("MeetingParcel");
// build notification pending intent to go to the details page when click on the body of the notification
Intent notificationIntent = new Intent(context, MeetingDetails.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
notificationIntent.putExtra("MeetingParcel", meeting); // send meeting that we received to the MeetingDetails class
notificationIntent.putExtra("notificationIntent", true); // flag to know where the details screen is opening from
PendingIntent pIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
// build intents for the call now button
Intent phoneCall = Call._callIntent(meeting);
if (phoneCall != null) {
PendingIntent phoneCallIntent = PendingIntent.getActivity(context, 0, phoneCall, PendingIntent.FLAG_CANCEL_CURRENT);
int flags = Notification.FLAG_AUTO_CANCEL;
// build notification object
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
Notification notification = builder.setContentTitle("Call In")
.setContentText(intent.getStringExtra("contextText"))
.setTicker("Call In Notification")
.setColor(ContextCompat.getColor(context, R.color.colorBluePrimary))
.setAutoCancel(true) // will remove notification from the status bar once is clicked
.setDefaults(Notification.DEFAULT_ALL) // Default vibration, default sound, default LED: requires VIBRATE permission
.setSmallIcon(R.drawable.icon_notifications)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(meeting.description))
.addAction(R.drawable.icon_device, "Call Now", phoneCallIntent)
.setCategory(Notification.CATEGORY_EVENT) // handle notification as a calendar event
.setPriority(Notification.PRIORITY_HIGH) // this will show the notification floating. Priority is high because it is a time sensitive notification
.setContentIntent(pIntent).build();
notification.flags = flags;
// tell the notification manager to notify the user with our custom notification
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notification);
}
}
}
use this flag:
Notification.FLAG_AUTO_CANCEL
inside this:
int flags = Notification.FLAG_AUTO_CANCEL;
Notification notification = builder.build();
notification.flags = flags;
Documentation
Ok turns out it's a known problem already, and it needs extra code to be done (keeping reference to notification through id). Have no clue why API does not provide this, as it seems very logical to do. But anyways,
see this answer in stackoverflow:
When you called notify on the notification manager you gave it an id - that is the unique id you can use to access it later (this is from the notification manager:
notify(int id, Notification notification)
To cancel, you would call:
cancel(int id)
with the same id. So, basically, you need to keep track of the id or possibly put the id into a Bundle you add to the Intent inside the PendingIntent?
I faced this problem today, and found that FLAG_AUTO_CANCEL and setAutoCanel(true), both work when click on notification,
but not work for action click
so simply, in the target service or activity of action, cancel the notification
NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancelAll();
or if have more notification
manager.cancel(notificationId);
You have created two pending intent use in boths and change Flag too.
PendingIntent pIntent = PendingIntent.getActivity(context, (int) System.currentTimeMillis(), notificationIntent, 0);
PendingIntent phoneCallIntent = PendingIntent.getActivity(context, (int) System.currentTimeMillis(), phoneCall, PendingIntent.FLAG_UPDATE_CURRENT);
// CHANGE TO THIS LINE
PendingIntent pIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
PendingIntent phoneCallIntent = PendingIntent.getActivity(context, 0, phoneCall, PendingIntent.FLAG_CANCEL_CURRENT);

NotificationCompat.Builder is creating notifications that are canceled after one notification is selected

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

How to add a Dynamic image instead of notification icon in android?

I used below code for displaying notification in notification Bar.
it worked fine.
But i need to display notification icon dynamically that will come from web service.
How i can do?
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification note = new Notification(R.drawable.image,"status message", System.currentTimeMillis());
Intent in = new Intent(Notify.this,CommentU.class);
PendingIntent pi = PendingIntent.getActivity(Notify.this, 0, in, 0);
note.setLatestEventInfo(Notify.this,"NotificationTitle", "You have a new Commentio", pi);
note.number = ++count;
note.vibrate = new long[] { 500l, 200l, 200l, 500l };
note.flags |= Notification.FLAG_AUTO_CANCEL;
nm.notify(NOTIFY_ME_ID, note);
Thanks in Advance.
I have one suggestion for you: you have to download that image which you want to show and then you can set that as bitmap: check below code. I have created one BITMAP.
its look link :
for this you have to add android-support-v4.jar
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("My notification").setLargeIcon(BITMAP)
.setContentText("Hello World!");
Intent resultIntent = new Intent(this, test.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(test.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(NOTIFY_ME_ID, mBuilder.build());
for more detail chekc this link.
Removing notifications
Notifications remain visible until one of the following happens:
The user dismisses the notification either individually or by using "Clear All" (if the notification can be cleared).
The user clicks the notification, and you called setAutoCancel() when you created the notification.
You call cancel() for a specific notification ID. This method also deletes ongoing notifications.
You call cancelAll(), which removes all of the notifications you previously issued.
Edited: just replace this.
mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("My notification").setLargeIcon(BITMAP)
.setAutoCancel(true)
.setContentText("Hello World!");
just add some icons in your resource folder and then
int myIcon = R.drawable.image;
your logic goes here ....
and change value of icon according to your logic like myIcon = R.drawable.somenewimage;
and then finally set your notification
Notification note = new Notification(myIcon,"status message", System.currentTimeMillis());

Categories

Resources