After reading multiple posts I have tried everything to generate a new notification for every alert using unique id. However this is not working. Following is my code:-
//Generate random id for notification
Random r=new Random();
int id=r.nextInt(9999);
PendingIntent intent =PendingIntent.getActivity(getApplicationContext(), id, notificationIntent, 0);
Builder notice2=new Notification.Builder(getApplicationContext())
.setContentTitle(call.getName())
.setAutoCancel(true)
.setContentIntent(intent)
.setContentText("Context")
.setSmallIcon(com.project.calltracker.R.drawable.ic_alert)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), com.project.calltracker.R.drawable.ic_logo));
startForeground(id, notice2.getNotification());
As you can see I am using a random integer as Id each time I generate a notification. But still I only get a single notification no matter how many times I startForeground is called??
Please help!
Thanks!
That's because there's always just ONE foreground service running. Services are singletons by nature, there can't be 2 instances of the same service running.
If you want to just send multiple notifications you should use the notification manager, notify() method
You dont have to generate a random id, using a sequence of ids will be more safe and ensure that all the ids are unique
PendingIntent intent = null;
Builder notice2=null;
int N = 1000; //set this value
for(int id=1;id<N; id++){
intent =PendingIntent.getActivity(getApplicationContext(), id, notificationIntent, 0);
notice2=new Notification.Builder(getApplicationContext())
.setContentTitle(call.getName())
.setAutoCancel(true)
.setContentIntent(intent)
.setContentText("Context")
.setSmallIcon(com.project.calltracker.R.drawable.ic_alert)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), com.project.calltracker.R.drawable.ic_logo));
startForeground(id, notice2.getNotification());
}
I hope it helps
Related
I am simultaneously developing two Android applications that are communicating with each other, and I am using notifications to show received messages. This is the code I am using to show a notification:
private void showNotification(String title, String content) {
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("default",
"NOTIF_CHANNEL",
NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("CHANNEL FOR INFORMING ABOUT MESSAGE RECEIVED");
mNotificationManager.createNotificationChannel(channel);
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext(), "default")
.setSmallIcon(R.mipmap.ic_launcher) // notification icon
.setContentTitle(title) // title for notification
.setContentText(content)// message for notification
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI) // set alarm sound for notification
.setAutoCancel(true); // clear notification after click
Intent intent = getPackageManager()
.getLaunchIntentForPackage(getPackageName())
.setPackage(null)
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
mBuilder.setContentIntent(pi);
mNotificationManager.notify(0, mBuilder.build());
}
In one of my applications, this works flawlessly every time, but in the other it never works. I am using the exact same code and running the applications on the same device.
I am curious as to if someone is able to identify or make a guess on factors that would make a difference here. I have tried using the same icon, title, content, and sound, but to no avail. Any help or suggestions would be greatly appreciated!
If your code is working in one app but not in the other, and the code is exactly the same, surely you are using distinct versions of support library and/or distinct targetSdkVersion. Set the same of the app which works in the other that doesn't works.
I am using XMPP (smack) to create a messaging application and I am sending notifications whenever I receive a new message. The problem is that if I receive messages from two different users I can only see the last notification. How can I change it? Here is my code.
Intent thisIntent = new Intent(mApplicationContext, ChatActivity.class);
thisIntent.putExtra("EXTRA_CONTACT_JID",contactJid);
PendingIntent contentIntent = PendingIntent.getActivity(mApplicationContext, 0, thisIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder b = new NotificationCompat.Builder(mApplicationContext);
b.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.fab_bg_mini)
.setTicker("Hearty365")
.setContentTitle("New message")
.setContentText(" You received a new message from " + contactJid)
.setContentIntent(contentIntent)
.setContentInfo("Info");
if(!ChatActivity.active){
b.setDefaults(Notification.DEFAULT_LIGHTS| Notification.DEFAULT_SOUND);
}
NotificationManager notificationManager = (NotificationManager) mApplicationContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, b.build());
And as you can see I put an extra contactJid which is important to me. I need to set it in such a way that if a user clicks one notification its contactJid will be this and if another its contactJid will be another.
notificationManager.notify(1, b.build()); is your problem - you need to supply a unique identifier for this notification, as per the documentation:
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.
You are supplying the constant 1 for each notification, instead of a unique ID. I'd suggest using a hash of the contact JID (which I assume is a string):
notificationManager.notify(contactJid.hashCode(), b.build());
i have an application about football/soccer , i'm using API for get information about the matches, i need a way to make a real time notification when a goal is added in this API which have a JSON format .
If you have access to your back end web service code, look into Google cloud messaging(gcm) service, it is made precisely for this purpose. If it is not feasible to use gcm, you need to set a repeating alarm, but it will not be as accurate as gcm. But I highly recommend going for gcm. Here's a link for your reference. GCM dev docs
Another work around for the case where you don't have access to source code for back end is to develop a middle layer sort of web service that keeps polling your back end and uses gcm to alert the clients. This way atleast you won't be wasting user's system resources.
This is how you pop a notification:
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.logo_notification)
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setVibrate(new long[] { 200, 200, 200})
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(id, notificationBuilder.build()); //id is the notification id, if you use the same id, the notification will override the previous
In order to achieve the functionality,
Use a service to frequently(maybe once in 5 minutes) check information about the match.
If you have any Updates, show a notification to the user.
To show Notification:
PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), 0);
Notification notification = new NotificationCompat.Builder(getApplicationContext()).setTicker("Ticker Text").setSmallIcon("Icon").setContentTitle("Title").setContentText("Content Text").setContentIntent(pi).setAutoCancel(true).build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, notification);
For more info use this link
here
What you really want to do is have a Receiver that will run and check for updates. For real time updates, I would use a Socket.
It pretty much depends on your server.
I an a noob in android, I am trying to show notification of the push notifications I receive. Every time I receive a push notification a new notification is created in the notification bar, even if an exisiting one is present. I want them to be grouped together.
This is what I am currently doing
private void generateNotification(Context context, String ticker, String title, String msg, int icon, Intent intent)
{
int notificationId = 1;
long when = System.currentTimeMillis();
int pendingNotificationsCount = AppName.getPendingNotificationsCount() + 1;
AppName.setPendingNotificationsCount(pendingNotificationsCount);
mNotifyBuilder = new NotificationCompat.Builder(this)
.setWhen(when)
.setContentTitle(title)
.setContentText(msg)
.setAutoCancel(true)
.setContentIntent(PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT))
.setNumber(pendingNotificationsCount);
//This prints the count correctly....
Log.d("Snehan", "Message built with Count "+pendingNotificationsCount);
Notification notif = mNotifyBuilder.build();
notif.defaults = Notification.DEFAULT_ALL;
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notificationId, notif);
}
Am I doing something wrong here or missing something??
Seems Android updated the library since I last used it. But the logic is still the same. You need to save whatever the notification id was or at least give it a name you can track and check if it exists. More info can be found in the Android docs. Below is a snippet from what I mean.
To set up a notification so it can be updated, issue it with a notification ID by calling NotificationManager.notify(ID, notification). To update this notification once you've issued it, update or create a NotificationCompat.Builder object, build a Notification object from it, and issue the Notification with the same ID you 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.
The docs have everything you need so no need for me to write the code for you :) Hope that helped.
Edit:
Ok, so I recommend you adda a dummy icon just to see what that does. I also recommend instead of chaining all that stuff only chain the text stuff. This way you can debug a bit easier. Try to follow the doc a bit more closely. I don;t really see anything wrong with your code, but obviously something is causing the issue.
Edit 2
So it seems the icon was the problem. I've had this issue before, which is why I mentioned to add that explicitly. Hopefully when someone encounters issues with notifications please make sure you have an icon!!
I am developing event reminder application in android.In my application user can set event time and i am generating status bar notification at the specified time.But in my application it generates the same notification(notification ID)at many times in status bar.Please help me how to avoid that?
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,i, PendingIntent.FLAG_ONE_SHOT);
notification = new Notification(R.drawable.logo, "Notification",System.currentTimeMillis());
notification.setLatestEventInfo(context,strText, "#"+strDate+ strCorrectTime,contentIntent);
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.defaults|=Notification.DEFAULT_ALL;
mNotificationManager.notify(Integer.parseInt(intent.getExtras().get("NotifyCount").toString()), notification);
this is coding..
don't use System.currentTimeMillis() as a notification id.
instead define a constant:
public static final long TRAY_ID = 237864827364; // let your IDE generate it
and use this before each mNotificationManager.notify(..):
( (NotificationManager)getSystemService( Context.NOTIFICATION_SERVICE ) ).cancel( TRAY_ID );
The System time should work fine.Plese check your BroadcastReceiver how many time called.
It may be called two times.
And use the for unique id for notification.
int notitime=new Random(System.currentTimeMillis()).nextInt();
mNotificationManager.notify(notitime, notification);
notitime is the unique id for the notification.