I want to show news GCm notification.
After receiving multiple message i want to show like 3 unread msg,4 unread msg.
Please help how can i do
(sorry for bad english)
Just count how many unread messages you have, build a notification and
use the [a NotificationManager.notify](http://developer.android.com/reference/android/app/NotificationManager.html#notify(int, android.app.Notification)) there are two versions one that accepts a notification id and the other accepts a tag and an id,
for both methods if there is already a notification with the same id or with the (id,tag) any previous notification is replaced by the new one.
Take a look into a this,
to see the available styles and patterns and use the one appropriated to your case, here's an example of how to do a Big Text or Inbox Style notification based on the number of messages
public static void updateOrSendNotification(Context context, String[] messages) {
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
int count = messages.length;
if (messages.length == 0) {
notificationManager.cancel(NOTIFICATION_ID);
return;
}
//Intent to be launched on notification click
Intent intent = new Intent(Intent.ACTION_VIEW,
null,
context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
int requestID = (int) System.currentTimeMillis();
PendingIntent contentIntent = PendingIntent.getActivity(context, requestID,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
String ticker = context.getString(R.string.new_notification_ticker);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context);
String contentTitle = context.getString(R.string.notification_text_style_title, messages.length);
mBuilder.setSmallIcon(R.drawable.ic_stat_notification)
.setTicker(ticker) // the thicker is the message that appears on the status bar when the notification first appears
.setDefaults(Notification.DEFAULT_ALL) // use defaults for various notification settings
.setContentIntent(contentIntent) // intent used on click
.setAutoCancel(true) // if you want the notification to be dismissed when clicked
.setOnlyAlertOnce(true); // don't play any sound or flash light if since we're updating
NotificationCompat.Style style;
if (count > 1) {
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
style = inboxStyle;
mBuilder.setContentTitle(contentTitle);
for (String r : messages) {
inboxStyle.addLine(r);
}
} else {
NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
style = bigTextStyle;
bigTextStyle.setBigContentTitle(messages[0].substring(0, 10).concat(" ..."));
bigTextStyle.bigText(messages[0]);
}
mBuilder.setStyle(style);
notificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
This method assumes you call it every time with all the new messages your app has received,
since the NOTIFICATION_ID is always the same any previous notification will be replaced by the new one,
You can test it like this
String[] messages = {
"hi john how are you ?",
"john you never told me if you'r doing ok !",
"john lets go out"
};
updateOrSendNotification(this, messages);
From your question I assume you are trying to show stacked notifications (updating the current notifications)
Here is a detailed way of managing and updating notifications: http://developer.android.com/guide/topics/ui/notifiers/notifications.html#Managing
Multiple notifications:
How to display multiple notifications in android
Related
I can't seem to figure out why I can'y get my actions to show up on a remote notification. I have seen several tutorials on making it happen, and followed them, still no actions show up. The end goal is to have a "Reply" action where you can type in a response and send a reply through the notification, much like the standard text message notification.
I couldn't get that to show up, so I decided to add a second action, that is just a basic action, neither are showing up. I'll post up my sendNotification method, hopefully someone can see what I am doing wrong...
private void sendNotification(String body, String id) {
Intent i;
PendingIntent pi;
if(user.role.equals(Strings.roleMember) { //This is just to separate logic
i = new Intent(this, NotificationReceiver.class);
pi = PendingIntent.getBroadcast(this, 0, i, 0);
} else {
i = new Intent(this, AgentChatActivity.class);
pi = PendingIntent.getActivity(this, 0, i, 0);
}
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtra(Strings.chatID, id);
RemoteInput input = new RemoteInput.Builder(Strings.textReply).setLabel("Reply").build();
NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(android.R.drawable.ic_dialog_info, "Reply", pi)
.addRemoteInput(input).build();
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, Strings.channelID)
.setSmallIcon(R.drawable.ic_stat_notify)
.setContentTitle("New Message")
.setContentText(body)
.setAutoCancel(true)
.setCategory(NotificationCompat.CATEGORY_MESSAGE) //I have tried without this too
.setPriority(NotificationCompat.PRIORITY_MAX)
.addAction(replyAction)
.addAction(android.R.drawable.ic_dialog_alert, "reply", pi); //this is the second I added just to test
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(Strings.channelID, "General Messages", NotificationManager.IMPORTANCE_HIGH);
manager.createNotificationChannel(channel);
}
manager.notify(0, builder.build());
}
According to everything I have seen online, that should have actions attached to the notification, however I run it in the emulator (Pixel 6 API 27) and the notification shows up, but no actions are on it. I have tried without the second action, I have tried with only the second action, nothing shows up, just the basic notification. My build settings are set to minSdk 21, compileSdk and targetSdk 33. I would be more than happy to post any more code or anything else anyone needs, I can't figure it out. Thank you.
I am sharing two images please have a look on it you will understand my problem
in fist image notification comes successfully as shown better me notification but
I want it to come and show first on main screen as shown in second image just this telegram notification.
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
// r.play();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
r.setLooping(false);
}
// vibration
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
long[] pattern = {100, 300, 300, 300};
v.vibrate(pattern, -1);
int resourceImage = getResources().getIdentifier(remoteMessage.getNotification().getIcon(), "drawable", getPackageName());
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "CHANNEL_ID");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder.setSmallIcon(R.mipmap.betterme);
} else {
builder.setSmallIcon(R.mipmap.betterme);
}
Intent resultIntent = new Intent(this, SplashScreen.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentTitle(remoteMessage.getNotification().getTitle());
builder.setContentText(remoteMessage.getNotification().getBody());
builder.setContentIntent(pendingIntent);
builder.setStyle(new NotificationCompat.BigTextStyle().bigText(remoteMessage.getNotification().getBody()));
builder.setAutoCancel(true);
builder.setOngoing(true);
builder.setPriority(NotificationCompat.PRIORITY_MAX);
builder.setSound(notification);
mNotificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelId = "Your_channel_id";
NotificationChannel channel = new NotificationChannel(
channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_HIGH);
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
channel.setSound(notification, audioAttributes);
mNotificationManager.createNotificationChannel(channel);
builder.setChannelId(channelId);
}
mNotificationManager.notify(100, builder.build());
}
}
first image
second image
If I understand correctly, you would like to have a heads up notification.
Note, that the android system decides when to make a notification a heads up notification and has the final say - not you the developer. Here you can find some examples when it does so: https://developer.android.com/guide/topics/ui/notifiers/notifications#Heads-up
Make sure that your setup reflects these. From your sample it seems to be the case, but maybe you have changed the notification channel settings (from the app settings), which override your code preferences (the user has precedence over the app).
Additionally, note that if you swipe the heads up notification in a upward direction (not sideways), Android starts a cool off time, where no heads up notifications from that app appears for a few seconds (or more). You can try that with Telegram or any other app as well. After the cool-off time, it starts showing up again like a heads up notification. This is a way Android utilises to prevent apps to be annoying to users.
Seems there is no problem in the notification. But your channel is already created with normal notification and you update to IMPORTANCE_HIGH for NotificationChannel.
Once the channel is created with priority it cannot be changed. So you can either change the channel id or uninstall and reinstall and test it.
My specific issue is that I am trying to construct a custom notification layout using NotificationCompat.Builder, and using setOnClickPendingIntent to send actions to a service running as part of my app.
Basically I can get as far as applying a specific RemoteViews object to the notification, which is all good, but when I try to call setOnClickPendingIntent() for a widget inside the RemoteViews object (say, an ImageButton) it creates a malformed notification which is caught as an IllegalArgumentException in logcat.
When I try to set these onClickPendingIntents for API > 10, it works with no real trouble but with Gingerbread it breaks the notification. (It allows me to build the layout but the onClick pending intents don't work), just as described in on of the comments on this issue:
https://code.google.com/p/android/issues/detail?id=30495
In a previous SO response, CommonsWare says "The functionality was never there in the first place" as of two years ago.
(Android: setOnClickPendingIntent in a statusbar notification on Gingerbread)
Is that still true? If I want to put notification buttons in a layout that works with API 10, am I basically SOL?
Try this :
private void generateNotification(Context context, String message) {
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
String appname = context.getResources().getString(R.string.app_name);
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
Notification notification;
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, myactivity.class), 0);
// To support 2.3 os, we use "Notification" class and 3.0+ os will use
// "NotificationCompat.Builder" class.
if (currentapiVersion < android.os.Build.VERSION_CODES.HONEYCOMB) {
notification = new Notification(icon, message, 0);
notification.setLatestEventInfo(context, appname, message,
contentIntent);
notification.flags = Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
} else {
NotificationCompat.Builder builder = new NotificationCompat.Builder(
context);
notification = builder.setContentIntent(contentIntent)
.setSmallIcon(icon).setTicker(appname).setWhen(0)
.setAutoCancel(true).setContentTitle(appname)
.setContentText(message).build();
notificationManager.notify(0 , notification);
}
}
Hope this helps.
My app is running a service that collects feeds. When it find these feeds it create notations (unsuccessfully). I use a method call like this:
doNotification(date,"New Article",title,link,content,description,false);
for articles and this:
doNotification(date,"New Video",title,link,"","",true);
for videos. The method is this:
public void doNotification(Date date,String title,String subtext,String url,String body,String dateString,boolean video){
long time = date.getTime();
if(time > feedGetter.lastFeed){
//New feed, do notification
NotificationManager mNotificationManager = (NotificationManager) feedGetter.service.getSystemService(Context.NOTIFICATION_SERVICE);
int icon = R.drawable.notification_icon;
Notification notification = new Notification(icon, title + ": " + subtext, time);
Intent notificationIntent = new Intent(feedGetter.service, NotificationActivity.class);
notificationIntent.putExtra("url",url);
notificationIntent.putExtra("video",video);
if(!video){
notificationIntent.putExtra("body",body);
notificationIntent.putExtra("date",dateString);
notificationIntent.putExtra("title",subtext);
}
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(feedGetter.service, 0, notificationIntent, PendingIntent.FLAG_ONE_SHOT);
notification.setLatestEventInfo(feedGetter.service.getApplicationContext(), title, subtext, contentIntent);
mNotificationManager.cancel(video? 1 : 0);
mNotificationManager.notify(video? 1 : 0, notification);
//Update new time if necessary.
if(time > feedGetter.newTime){
feedGetter.newTime = time; //New time will be the time for this feed as it is the latest so far
}
}
}
As you see I add some data to the intent so I can handle the notifications correctly. The notifications are assigned to an ID for videos or an ID for articles and should replace the previous notifications. Here is the NotificationActivity that handles the notifications:
public class NotificationActivity extends Activity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Debug.out("Notification Activity");
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if(getIntent().getBooleanExtra("video", true)){
//Handle video notification
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(getIntent().getStringExtra("url")));
startActivity(browserIntent);
mNotificationManager.cancel(1);
}else{
//Start application UI and move to article
Intent intent = new Intent(this,TheLibertyPortalActivity.class);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("url", getIntent().getStringExtra("url"));
intent.putExtra("body", getIntent().getStringExtra("body"));
intent.putExtra("date", getIntent().getStringExtra("date"));
intent.putExtra("title", getIntent().getStringExtra("title"));
startActivity(intent);
mNotificationManager.cancel(0);
}
finish();
}
}
So it's supposed to activate a URL for the videos and restart the application for articles with some data for handling the articles so the article is displayed to the user.
Seems simple enough but it doesn't work. The notifications display and they replace each other on the notification menu, showing the latest notifications for videos and articles but when I click on them they go wrong. I try to click on the article notification and it thinks it is a video and loads one of the videos. I go back onto the notification menu and the video notification has disappeared even when I clicked on the article notification. I try clicking on the article notification and nothing happens. It literally closes the menu and doesn't nothing and the notification remains in the menu doing nothing.
Thank you for any help with this. I am targeting the Google APIs level 14 API, with a min SDK version of level 8, trying with a 2.2.1 Android tablet.
The problem is with the Pending intent. Even though the docs say the requestCode is not used, it is. You must pass a unique integer for each PendingIntent. That worked!
I am trying to create multiple notifications in my application. To identify each notification uniquely, i have given them an unique identificationId. Following is my code:
private void updateNotification(int notificationId, int clockStatusID, CharSequence text) {
//notificationManager.cancel(notificationId);
// throws up an ongoing notification that the timer is running
Log.i("TIMERCOUNT", "Notification id: " + notificationId);
Notification not = new Notification(clockStatusID, // the
// icon
// for
// the
// status
// bar
text, // the text to display in the ticker
System.currentTimeMillis() // the timestamp for the
// notification to appear
);
Intent intent = new Intent();
intent.putExtra("notificationID", notificationId);
intent.setAction("actionstring" + System.currentTimeMillis());
intent.setClassName("com.chander.time.android.activities",
"com.chander.time.android.activities.Tabs");
not.setLatestEventInfo(self,
getText(R.string.timer_notification_title),
getText(R.string.timer_on_notification_text), PendingIntent
.getActivity(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT));
not.flags += Notification.FLAG_ONGOING_EVENT;
not.flags += Notification.FLAG_NO_CLEAR;
notificationManager.notify(notificationId, not);
}
Problem:
When a notification is selected, Tabs activity is called passing the intent. I want to access the unique notificationId of the notification that was selected in Tabs. I tried intent.putExtra() to save the notificationId in the intent. But, for multiple notifications its overwriting the notificationId and returns the latest one. I dont understand as to why this is happening and how can i avoid this overwriting of notificationId.
Thanks,
Chander
I got the answer. The intents were getting cached in. To, make a new intent, just add the following piece of code:
saveCallIntent.setData((Uri.parse("custom://"+System.currentTimeMillis())));
This makes the intent unique.
Also, someone suggested me the following piece of code to make the intent unique:
saveCallIntent.setAction("actionstring" + System.currentTimeMillis());
It didnt help me, but might be of help to someone else.
--Chander
just place the notificationId instead of 0 in pendingIntent.
PendingIntent.getActivity(this, notificationId, intent,PendingIntent.FLAG_UPDATE_CURRENT));
The user must also update the following code together with the above one to get it working.
mNotificationManager.notify(notificationId, mBuilder.build());