I am writing an application and in this application I need to set multiple notification with same intent just like open my application whenever user tap on any notification.
All the notification comes on different time and date without having any data but the problem is, if I set two notification for 03:27 PM and 03:28 PM then the first notification (03:27 PM) is canceled (Overwritten by second) and second is working correctly.
I am currently using this code for achieving this goal:
this method is used to set notification from Activity:
public static void setNotificationOnDateTime(Context context, long fireTime)
{
int requestID = (int) System.currentTimeMillis();
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, NotificationReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, requestID, i, 0);
am.set(AlarmManager.RTC_WAKEUP, fireTime, pi);
}
and my NotificationReceiver class look like this:
NotificationManager nm;
#Override
public void onReceive(Context context, Intent intent) {
Log.w("TAG", "Notification fired...");
nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent;
Bundle bundle = intent.getExtras().getBundle("NotificationBundle");
if(bundle == null)
{
contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, SplashScreen.class), 0);
}
else
{
contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, MenuScreen.class)
.putExtra("NotificationBundle", bundle), 0);
}
Notification notif = new Notification(R.drawable.ic_launcher,
"Crazy About Android...", System.currentTimeMillis());
notif.setLatestEventInfo(context, "Me", "Message test", contentIntent);
notif.flags |= Notification.FLAG_AUTO_CANCEL;
nm.notify(1, notif);
}
I alerady spend a lot time on googling and found some solutions but they didn't work for me here is the link of some of them:
android pending intent notification problem
Multiple notifications to the same activity
If any one knows how to do this please help me.
Quote:
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.
But you're always using 1 for the id parameter. Use a unique ID when you post several notifications.
Update If that doesn't help, you can still create Intents which do not compare as being equal, while having an equal effect.
this may be helpful
notif.flags |= Notification.FLAG_ONGOING_EVENT;
the notification will never close...
Try to set as below :
contentIntent=PendingIntent.getActivity(p_context, i, new Intent(context, MenuScreen.class),PendingIntent.FLAG_CANCEL_CURRENT);
It might help you.
Related
I am trying to implement multiple notifications for each reminder I have in my app. I found some leads around here that it could be achieved using unique id per each notification but it is not working I get only one notification which is overwritten by the last one set. Also I would like know how is it possible to keep the notification intact after device is rebooted please. Here is my code
//call notification activation Intent
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
AlarmReceiver class
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//creating unique id for each specific notification
int ID = (int) ((new Date().getTime()/1000L) % Integer.MAX_VALUE);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notification = new Intent(context,MainActivity.class);
notification.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pi = PendingIntent.getActivity(context,0,notification,0);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mynotification = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_date_range_black_48dp)
.setContentTitle("note taker")
.setContentText("you have a reminder about a note")
.setAutoCancel(true)
.setContentIntent(pi)
.setSound(defaultSoundUri)
.setVibrate(new long[]{1000,1000,1000,1000,1000});
notificationManager.notify(ID,mynotification.build());
}
}
I found some leads around here that it could be achieved using unique id per each notification but it is not working i get only one notification which is overwritten by the last one set
I think the problem lies not in your notification, but in your AlarmManager.
Try using different ID for each PendingIntent, and set the flag to PendingIntent.FLAG_ONE_SHOT.
Your calling intent should look like this:
//call notification activation Intent
Intent intent = new Intent(getBaseContext(), AlarmReciever.class);
int RQS_1 = (int) System.currentTimeMillis();
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
Try to give different request code and PendingIntent.FLAG_UPDATE_CURRENT as Flag for Pending Intent and check like this,
PendingIntent pi = PendingIntent.getActivity(context, new Random().nextInt(1000000), notification, PendingIntent.FLAG_UPDATE_CURRENT);
Let's say a notification using AlarmManager was set at a specific date. What if I want to delete that notification with a button press before it has even appeared. The NotificationManager.cancel(id) method if I'm not mistaken will cancel a notification that is currently showing. What if I want to delete it before it has even appeared? Like how you remove an item in an arraylist or how you delete a row in a database.
Example I have a Personobject with id,name and everytime I add a Personto the database, a Notification will be set on a specified date.
Here is the set notification method to be called with a calendar instance of a specified date and a person object:
public void setNotification(Calendar calendar,Person person){
AlarmManager alertManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Intent intent = new Intent();
intent.setAction("android.media.action.DISPLAY_NOTIFICATION");
intent.addCategory("android.intent.category.DEFAULT");
intent.putExtra("myTag",person);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, person.getId(), intent, PendingIntent.FLAG_ONE_SHOT);
alertManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
My alarm receiver class (Yes I'm implementing DAO design pattern. I have a PersonDao and PersonDaoImpl with the latter being a singleton class):
public class AlarmReceiver extends BroadcastReceiver {
final static String GROUP_KEY = "GROUP_KEY";
#Override
public void onReceive(Context context, Intent intent) {
//retrieve info:
PersonDAO personDao = PersonDAOImpl.getInstance(context);
Person person = (Person)intent.getSerializableExtra("myTag");
String name = person.getName();
long[] vibrationPattern = {0, 300, 0, 300};
Intent notificationIntent = new Intent(context, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(ViewDetails.class);
stackBuilder.addNextIntent(notificationIntent);
int requestCode = person.getId();
PendingIntent pendingIntent = stackBuilder.getPendingIntent(requestCode, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
Notification notification = builder.setContentTitle("Deadline due today")
.setContentText("name: " + name)
.setTicker(name+"'s debt is due today")
.setSmallIcon(R.mipmap.ic_launcher)
.setPriority(Notification.PRIORITY_MAX)
.setContentIntent(pi)
.build();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(requestCode, notification);
}
Example the date set on the alarm reciever was September 12 2016 3:00pm. The current date is Septermber 10 2016. What I want to do is when I delete the person in the database, the notification will be deleted/canceled also therefore on September 12 2016 3:00pm there will no longer be an alarm notification.
If you want to cancel something that you scheduled via AlarmManager, call cancel() on AlarmManager, passing in an equivalent PendingIntent to the one that you used to schedule the work in the first place. Here, by "equivalent PendingIntent", I mean:
the same operation (e.g., getActivity() vs. getService() vs. getBroadcast())
the same request code (2nd parameter to those methods)
an equivalent Intent
By "equivalent Intent", I mean:
the same component
the same action
the same MIME type
the same categories
the same data (Uri)
for whatever of those properties you had set on the original Intent for the original PendingIntent.
i trying do a "read more" after user click on notification.
What i need, start new Activity with unique extra content "id", "title" and "text".
My code:
void notificationSend(String id, String bar, String title, String text, String image, int delay) {
Bitmap bitmap = getBitmapFromURL(image, 130);
if(bitmap == null){
bitmap = getBitmapFromURL("https://pp.vk.me/c621316/v621316641/119d5/HB9s2z5mX-s.jpg", 130);
}
Intent notificationIntent = new Intent(this, SingleNewsActivity.class);
notificationIntent.putExtra("id", id);
notificationIntent.putExtra("title", title);
notificationIntent.putExtra("text", text);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentIntent(contentIntent);
builder.setSmallIcon(R.drawable.ic_bitcoin_notification);
builder.setLargeIcon(bitmap);
builder.setTicker(bar);
builder.setContentTitle(title);
builder.setContentText(text);
builder.setWhen(System.currentTimeMillis());
builder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
Notification notification = builder.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
try {
notificationManager.notify(new Integer(id), notification);
sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
And it do next thing, lets send 2 notifications, after i click on first, activity started but with extra data from second notification, why?
The issue is due to using : FLAG_UPDATE_CURRENT
if you see document for this flag:
Flag indicating that if the described PendingIntent already exists, then keep it but replace its extra data with what is in this new Intent. For use with getActivity(Context, int, Intent, int), getBroadcast(Context, int, Intent, int), and getService(Context, int, Intent, int).
This can be used if you are creating intents where only the extras change, and don't care that any entities that received your previous PendingIntent will be able to launch it with your new extras even if they are not explicitly given to it.
in your case, you are updating just extra and due to that, the value of extras get updated.
For solution of your issue, you should pass request code unique for all case:
Currant code:
PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Actual:
PendingIntent.getActivity(this, unique_code, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
So The reason is that you are setting unique id to the notification, lets suppose id value is 1 when your 1st notification comes then the notification object is created with that id, when you second notification come then your id is again 1 so your notification is updated and when you click on it you get the second notification.
what you can do is set the different id for notifications. have a look at below code
private NotificationManager mNotificationManager;
private NotificationCompat.Builder builder;
write below code inside a function
mNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
Random random = new Random();
int NOTIFICATION_ID = random.nextInt(9999 - 1000) + 1000;
Intent intent = new Intent(this, SingleNewsActivity.class);
Bundle bundle = new Bundle();
bundle.putExtra("id", id);
bundle.putExtra("title", title);
bundle.putExtra("text", text);
intent.putExtras(bundle);
PendingIntent contentIntent = PendingIntent.getActivity(this, NOTIFICATION_ID,
intent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("TITLE")
.setStyle(new NotificationCompat.BigTextStyle().bigText("ASD"))
.setContentText("Summary").setAutoCancel(true);
mBuilder.build().flags |= Notification.FLAG_AUTO_CANCEL;
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
Log.d("", "Notification sent suessfully.");
in the above code whenever you will receive notification you will get a unique code in NOTIFICATION_ID
I am having an issue where, no matter what notification the user touches, I am always receiving the same notification, even though it is cancelled.
The first notification a user touches is the only notification that will ever be delivered to my pending intent, until device reboot (then the first touched notification becomes the new Hotel California notification).
Here is how I am constructing the notifications:
final Bundle extras = new Bundle();
final int notificationId = Integer.parseInt(payload.getObjectId());
extras.putInt(NOTIFICATION_ID, notificationId);
final Intent intent = new Intent(context,
PushNotificationLauncherActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtras(extras);
final NotificationCompat.Builder builder = new NotificationCompat.Builder(
context);
builder.setContentTitle(context.getString(R.string.app_name));
builder.setContentText(payload.getText());
builder.setSmallIcon(R.drawable.icon_launcher);
builder.setAutoCancel(true);
final PendingIntent pIntent = PendingIntent.getActivity(context, 0,
intent, 0, extras);
builder.setContentIntent(pIntent);
final Notification notification;
if (Build.VERSION.SDK_INT < 16) {
notification = builder.getNotification();
} else {
notification = builder.build();
}
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(notificationId, notification);
Then I have this in my PushNotificationLauncherActivity:
final Bundle extras = getIntent().getExtras();
final int notificationId = extras
.getInt(SocialcastGoogleCloudMessageReceiver.NOTIFICATION_ID);
final NotificationManager notificationManager = (NotificationManager) this
.getSystemService(NOTIFICATION_SERVICE);
// please go away
notificationManager.cancel(notificationId);
Log.d(PushNotificationLauncherActivity.class.getSimpleName(),
"Touched notification ID: " + String.valueOf(notificationId));
No matter which notification I touch, in the log Touched notification ID: 1234 will always show, even if the notification I touch on has an ID of 56789.
I highly doubt it is an issue with my test-device, but incase it helps; I am using a 2013 Nexus 7 with KitKat 4.4.4 with the Dalvik runtime (not ART) Build KTU84P.
Pass your notificationId as the request code here:
final PendingIntent pIntent = PendingIntent.getActivity(context, 0,
intent, 0, extras);
Change this to:
final PendingIntent pIntent = PendingIntent.getActivity(context, notificationId,
intent, 0, extras);
When comparing two Intent instances, the included Bundles are not compared. So, from android's point of view, the two intents are the same.
Interestingly, the reqCode (second argument in PendingIntent.getActivity(...)) is compared. And this should render your Intents unique.
I wrote an app and I set an alarm manager which set to send a notification every 3 hours. Assume my notification has to be send at 11:10 and my phone is getting off at 11:00. So, I will not receive any notification. When my phone is turned on, I will receive the next notification at 2:10, so everything is working correctly.
Although, it was observed that I will not receive any notification after my phone is getting off for two round of notification. Do you have any suggestion?
The code is provided:
Intent intentAlarm = new Intent(this, NotifyBroadcast.class);
PendingIntent pintentAlarm = PendingIntent.getBroadcast(this, 0, intentAlarm, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
// Start every 30 seconds
mgr.setRepeating(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis(), 300, pintentAlarm);
// NotifyBroadcast:
public class NotifyBroadcast extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent resultIntent = new Intent(context, MainActivity.class);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
context,
0,
resultIntent,
0
);
Notification notification = new Notification(R.drawable.ic_launcher, "Let me know what is your emotion buddy!", System.currentTimeMillis());
notification.defaults |= Notification.DEFAULT_SOUND;
notification.sound = Uri.parse("file:///sdcard/notification/notification.mp3");
//notification.flags = Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(context, "emotion interface", "Let me know what is your emotion buddy!", resultPendingIntent);
int mId = 001;
// mId allows you to update the notification later on.
mNotificationManager.notify(mId, notification);
// mNotificationManager.notify(mId,mBuilder.build());
// mNotificationManager.cancel(mId);
}
}
I didn't understand following part very well :
I will not receive any notification after my phone is getting off for two round of notification .
Just check that you are relaunching your service after reboot. For that you need to add a receiver that launches your Service again after the reboot. You need to handle that on android.intent.action.BOOT_COMPLETED intent broadcast. Some of the questions that might help you are:
Android: make notification persist across phone reboot
android notification after reboot
Android: why did the Alarm notification stop after system reboot
Hope this helps in some way.