Android notifications with multiple groups - android

I implemented "Direct Reply" for the notifications in my app.
How do I implement multiple direct replies?
For example, if the user receives messages from two different people, I want him to be able to reply to each one of them through the notification.
Here is my code:
notificationBuilder.setContentTitle(title)
.setContentText(text);
NotificationCompat.InboxStyle expandedStyle = new NotificationCompat.InboxStyle();
expandedStyle.setBigContentTitle(title);
for (String key : mMessageList.keySet()) {
for (String message : mMessageList.get(key)) {
expandedStyle.addLine(message);
}
}
expandedStyle.setSummaryText(summary);
notificationBuilder.setStyle(expandedStyle);
String replyLabel = context.getString(R.string.reply_to, name);
RemoteInput remoteInput = new RemoteInput.Builder(KEY_TEXT_REPLY)
.setLabel(replyLabel)
.build();
NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(
R.drawable.reply, replyLabel, getReplyPendingIntent(context))
.addRemoteInput(remoteInput)
.build();
notificationBuilder.addAction(replyAction);
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(NOTIFICATION_ID, notificationBuilder.build());

When creating multiple notifications for a handheld device, you should always aggregate similar notifications into a single summary notification.
Check here this shows how to build multiple notification as groups.

Related

How to style a received message notification to look like a other sms notifications

I have implemented a Broadcast Receiver that listens for new messages in Xamarin Android and I get the Originating Address and the message body of the Sms and the I set the earlier as the title of the notification and the later as the body of the notification. There is just one problem, my notification does not look like the notifications of the usual sms app as for the notification of the usual sms app then it has a drop down that when clicked the entire message body can be seen with a button for calling the sender or replying. The body of my notification does not show the message that exceeds the screen. I think it should break and fit the message inside the notification container but that does not happen. help me make my app display the message received in an inbox style fashion and to display like other apps. I am using the following Xamarin Android code
[BroadcastReceiver(Permission =Manifest.Permission.BroadcastSms,Enabled = true)]
[IntentFilter(new string[] {Telephony.Sms.Intents.SmsDeliverAction})]
//define the class that implements this broadcast receiver
public class SMSReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
if (intent.Action == Telephony.Sms.Intents.SmsDeliverAction)
{
Toast.MakeText(context, "new sms received", ToastLength.Short).Show();
//publish a notification on this new sms received
Bundle bundle = intent.Extras;
SmsMessage[] msgs = null;
var smsText = new Java.Lang.StringBuilder();
if (Build.VERSION.SdkInt > BuildVersionCodes.Kitkat)
{
msgs = Telephony.Sms.Intents.GetMessagesFromIntent(intent);
foreach(var text in msgs)
{
smsText.Append(text.MessageBody+"\n");
}
}
//declare the notification id
int notification_id = 0;
var inbox = new NotificationCompat.InboxStyle();
inbox.SetBigContentTitle(msgs[0].OriginatingAddress);
foreach(var text in msgs)
{
inbox.AddLine(text.MessageBody + "\n");
}
//build the notification for the message
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.SetSmallIcon(Resource.Drawable.ic_chat).SetLargeIcon(BitmapFactory.DecodeResource(Resources.System, Resource.Drawable.ic_chat))
.SetAutoCancel(true)
.SetStyle(inbox)
.SetDefaults(NotificationCompat.DefaultAll);
//call the notification manager so it can build and deliver the
//message to the os
NotificationManager notificationManager=(NotificationManager)context.GetSystemService(Context.NotificationService);
//android 8 introduced a new requirement for setting the notification id using
//a notification channel
if (Build.VERSION.SdkInt >= BuildVersionCodes.Q)
{
string channel_Id= "channel_id";
NotificationChannel channel = new NotificationChannel(channel_Id, "Channel human readable content", NotificationImportance.Default);
notificationManager.CreateNotificationChannel(channel);
builder.SetChannelId(channel_Id);
;
}
notificationManager.Notify(notification_id,builder.Build());
}
}
}

How to stop deleting or updating the first comment from notification bar android

I am a new application developer.I create code to see if there are any new comments in my database. It's work fine but I have one problem new I can receive the first comment.But if you receive a second comment, the first comment will be updated and deleted, and the new or second comment will take its place.I do not need to delete the first comment I need to receive all comments to the user.How I con do that?
I need to show them all in case the user has not deleted or opened them In the notification bar.
For example like this image will by show:
Notifications code:
public void Notification(){
String url = "https://xxxxxxxxxx/Notification.php?UId="+UId;
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("data");
JSONObject hit = jsonArray.getJSONObject(0);
String id = hit.getString("id");
Intent activityIntent = new Intent(MainActivity.this, MainActivityFargmainMarket.class);
PendingIntent contentIntent = PendingIntent.getActivity(MainActivity.this, 0, activityIntent, 0);
int lastThread = Integer.parseInt(String.valueOf(id));
if (app.getTotal_threadss() <lastThread) {
app.setTotal_threadss(lastThread);
Notification notification = new NotificationCompat.Builder(MainActivity.this, CHANNEL_1_ID)
.setSmallIcon(android.R.drawable.ic_popup_reminder)
.setContentTitle("title")
.setContentText("text")
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setContentIntent(contentIntent)
.build();
notificationManager.notify(1, notification);
}
} catch(JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(request);
}
Android notifications are dependent on the Channel ID. If this is a fixed CHANNEL_1_ID android will delete the message with the same ID. You should change the channel id dynamically as you create new push notification. Looking at your code you can use the id value of the comment:
Notification notification = new NotificationCompat.Builder(MainActivity.this, CHANNEL_1_ID)
.setSmallIcon(android.R.drawable.ic_popup_reminder)
.setContentTitle("title")
.setContentText("text")
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setContentIntent(contentIntent)
.build();
notificationManager.notify(**id**, notification);
Per documentation:
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 cancelled, it will be replaced by the updated information.

Android - Notification received but no notification popup (Foreground)

My app is receiving the notification correctly but is failing to show a notification pop up with the received info (If the app is opened).
N.B.: In case if the app is in the background, the notifications are displayed without any issue.
My Code:
I receive the notification in this method:
#Override
public void onMessageReceived(RemoteMessage remoteMessage)
{
Log.d(TAG, "From: " + remoteMessage.getFrom());
if(remoteMessage!=null)
{
String id = null;
String title = null;
String body = null;
String launchPage = null;
if(remoteMessage.getNotification()!=null)
{
title = remoteMessage.getNotification().getTitle();
body = remoteMessage.getNotification().getBody();
}
if(remoteMessage.getMessageId()!=null)
{
id = remoteMessage.getMessageId();
}
Log.i(TAG, "id: " + id);
Log.i(TAG, "title: "+ title);
Log.i(TAG, "body: " + body);
int notif_id = 0;
sendNotification(notif_id, title, body, launchPage);
}
}
then it calls this one (which is supposed to show the notification as i understand):
private void sendNotification(int id, String title, String messageBody, String launchPage)
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(android.R.drawable.stat_sys_download)
.setContentTitle("OMR - "+title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setColor(ContextCompat.getColor(this, R.color.colorPrimary))
.setChannelId(CHANNEL_ID);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createChannel(notificationManager, CHANNEL_ID);
}
Toast.makeText(this, "Received a notif...", Toast.LENGTH_SHORT).show();
//this line is not showing a notification
notificationManager.notify(id, notificationBuilder.build());
}
Firebase notification
{
"data": {
"message": "data payload only used to force using OnMessageReceived() if in BACKGROUND",
"notif_id": 1
},
"to" : "e04OAVaRw30:APA91bGyv5_tt4IWRkurjlqkqNlCxTBV8oRne18tQ5puniHPItOMgg11kdt56t5jfZnasb4Ms-tH9xUgWQhHy2eM487llRtlM9_V_PoWJI9KSr6XgCaysiDyS",
"notification": {
"title": "Notification",
"body": "This is Notification 2",
"sound":"default"
}
}
Result
the notification is built correctly
sound played correctly
notif put in system tray
BUT no notification popup appears (i have to show a
custom dialog for that)
My Problem lies in this specific line
notificationManager.notify(id, notificationBuilder.build());
which is failing to show the notification
Update
i have read more about Android notifications in
https://developer.android.com/guide/topics/ui/notifiers/notifications
and found out that notifications only show in the notification drawer without popping up (as Heads-up notifications).
and according to this question, i can force the notifications to show as Heads-up notifications if i added a high priority to them. Unfortunately this is not working either.
This image explains it all if you are using FCM.
Well, in my case some of the data I'm passing into the message body is null in the onReceived.
Fixed that and my notification popup was showing again
Change
val notificationManager = packageContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
to
val notificationManager = NotificationManagerCompat.from(packageContext.applicationContext)
helps to me

Android push notification logs onMessageReceived but not displaying on device

I am sending some push notifications to android from AWS,
the notification process is working registering the device, and I indeed get the test notifications, but only showing on the log, not on notification bar on top of the screen like any other notification would...
public void onMessageReceived(RemoteMessage remoteMessage) {
// ...
// TODO(developer): Handle FCM messages here.
Log.d("mako", "A From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d("mako", "B Message data payload: " + remoteMessage.getData());
if (/* Check if data needs to be processed by long-running job */ true) {
// For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
// scheduleJob();
} else {
// Handle message within 10 seconds
// handleNow();
}
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d("mako", "C Message Notification Body: " + remoteMessage.getNotification().getBody());
}
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
}
So, I send a test notification:
{
"GCM": "{ \"data\": { \"message\": \"test message\" } }"
}
And I can see in my console log the message test:
10-05 14:57:08.827 23062-23296/com.sb.comm D/mako: B Message data payload: {message=test message}
But is not showing on the little pop-up, What is missing to show the actual push notification on the screen?
Cheers
You have to Generate Notification on your device like this
public void onMessageReceived(RemoteMessage remoteMessage) {
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("App Name")
.setBadgeIconType(R.drawable.ic_notification)
.setLargeIcon(BitmapFactory.decodeResource(
getResources(),R.drawable.ic_notification))
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentText(remoteMessage.getData().get("body"));
NotificationManager notificationManager =
(NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(141, notificationBuilder.build());
}
Here Notification Builder will get data from your server notification payload and generate a notification on device.
please add these lines of code to show notification on notification bar.
Intent intent = new Intent(this, YourActivity.class);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notificationBuilder = new
NotificationCompat.Builder(this, "my_chanel_id");
notificationBuilder.setSmallIcon(R.drawable.ic_launcher_app);
notificationBuilder.setContentTitle("Titlee");
notificationBuilder.setContentText("anyText");
notificationBuilder.setAutoCancel(true);
notificationBuilder.setSound(uri);
notificationBuilder.setContentIntent(resultPendingIntent);
NotificationManager notificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String CHANNEL_ID = "my_channel_01";// The id of the channel.
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel("mychanelId",
"hyperlocal", importance);
notificationManager.createNotificationChannel(mChannel);
}
notificationManager.notify(message_id, notificationBuilder.build());
Turns out it was to do with the formatting of the body, it is not as suggested by >>> SNS "JSON message generator"
the body should be in this format:
{
"GCM": "{ \"notification\": { \"text\": \"test message\" } }"
}

Stacked notifications not working on closed app

I get the stacked notifications working if the app is opened but not when the app is closed. If the app is closed the icon is incorrect and the notifications are not stacked?
Here is my code:
notification = new NotificationCompat.Builder(this);
notification.setContentTitle(notifyFromName);
notification.setContentText(notifyMsg);
if (!msgIsProj) {
String followText = notifyMsg + " you!";
notification.setContentText(followText);
notification.setGroup(GROUP_KEY_FOLLOWERS);
Log.d(Constants.DEBUG, "SETTING AS FOLLOWers" + unread_notif);
} else {
notification.setContentText(notifyMsg + " " + notifyItemName);
notification.setGroup(GROUP_KEY_PROJECTS);
}
notification.setTicker(getString(R.string.titlePushNotify));
notification.setSmallIcon(R.drawable.ic_pushnotify);
//notification.setGroupSummary(true);
PendingIntent contentIntent = PendingIntent.getActivity(this, id,
newIntentMsg, PendingIntent.FLAG_CANCEL_CURRENT);
notification.setContentIntent(contentIntent);
notification.setAutoCancel(true);
manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if(notifyMsg != null && !notifyMsg.equals("")) {
manager.notify(id, notification.build());
unread_notif++;
Log.d(Constants.DEBUG, "PRE MORE NOTIF" + unread_notif);
if (unread_notif>1) {
Log.d(Constants.DEBUG, "GETTING MORE NOTIF" + unread_notif);
Notification summaryNotification = new NotificationCompat.Builder(this)
.setContentTitle("Your summary message")
.setSmallIcon(R.drawable.ic_pushnotify)
.setStyle(new NotificationCompat.InboxStyle()
.addLine("Details about your first notification")
.addLine("Details about your second notification")
.setBigContentTitle(Integer.toString(unread_notif)+" new notifications")
.setSummaryText("More details in app"))
.setGroup(GROUP_KEY_FOLLOWERS)
.setGroupSummary(true)
.build();
manager.notify(id++, summaryNotification);
}
}
For Firebase notifications,onMessageReceive is called when the app is in the foreground if you app if is background, the Google Services will take care of displaying your message.
Now notifications are handled using two ways:
- notification payload
- data payload
Notifications are managed when the app in the foreground using DATA Payload and using NOTIFICATION payload they are handled when the app in background or killed.
So, the solution for this is ditch the notification object from your message payload. Removing the notification object at backend will consider data payload object as default as you won't face this problem anymore.

Categories

Resources