Whatsapp like notification in android wear - android

I need to achieve notification in android wear like in whatsapp where each conversation is a list and sliding to the right allows the user to reply to the respective conversation. I tried stacking from the android developers example but it only displays messages as is. How could I set more than 1 message and respective action like in whatsapp?
Edit:
NotificationCompat.WearableExtender wearOptions =
new NotificationCompat.WearableExtender()
.setHintHideIcon(true);
String replyLabel = mXmppConnectionService.getResources().getString(R.string.wear_reply);
RemoteInput remoteInput = new RemoteInput.Builder(EXTRA_VOICE_REPLY)
.setLabel(replyLabel)
.build();
Intent replyIntent = new Intent(mXmppConnectionService, XmppConnectionService.class);
PendingIntent replyPendingIntent =
PendingIntent.getActivity(mXmppConnectionService, 0, replyIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Action action =
new NotificationCompat.Action.Builder(R.mipmap.ic_launcher,
"reply to", replyPendingIntent)
.addRemoteInput(remoteInput)
.build();
final Builder mBuilder;
mBuilder.setDefaults(0);
mBuilder.setSmallIcon(R.drawable.ic_notification);
mBuilder.setPriority(getPriority());
mBuilder.setDeleteIntent(createDeleteIntent());
mBuilder.setLights(0xff00FF00, 2000, 3000)
.extend(wearOptions)
.extend(new NotificationCompat.WearableExtender().addAction(action));
final Notification notification = mBuilder.build();
notificationManager.notify(NOTIFICATION_ID, notification);

you are missing essentially three different things:
you are not calling setGroup("GROP_NAME") on your NotificationBuilder
Notifications that belong to the same group must have different ids. If you notify always with the same id, NOTIFICATION_ID in your case, ste stacking will not work
you want a different replyPendingIntent for each notification, otherwise your pending intent will refer to the last notification notified. Instead of hard-coding 0, pass a different value for each notification.
The rest looks good,

Related

How to display multiple notification as a group?

here is my code for notification. it generate a new notification each time
Random random = new Random();
int m = random.nextInt(9999 - 1000);
NotificationCompat.Builder mBuilder =new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.quemark1)
.setContentTitle("New Message")
.setContentText(message)
Intent intent = new Intent(this, ActivityMain.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(ActivityMain.class);
stackBuilder.addNextIntent(intent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);
mBuilder.setAutoCancel(true);
mNotificationManager.notify(m, mBuilder.build());
here is the output of my code
It will generate notification with multiple messages like Gmail
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.quemark1)
.setContentTitle("Title")
.setContentText("New Message received");
NotificationCompat.InboxStyle inboxStyle =
new NotificationCompat.InboxStyle();
inboxStyle.setBigContentTitle("doUdo");
// Add your All messages here or use Loop to generate messages
inboxStyle.addLine("Messgare 1");
inboxStyle.addLine("Messgare 2");
.
.
inboxStyle.addLine("Messgare n");
mBuilder.setStyle(inboxStyle);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addNextIntent(intent);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pIntent);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE);
mBuilder.setAutoCancel(true);
mNotificationManager.notify(0, mBuilder.build());
When creating notifications for a handheld device, you should always aggregate similar notifications into a single summary notification.
Check this it shows how to build stack notification.
private void sendStackNotificationIfNeeded(RemoteNotification remoteNotification) {
// only run this code if the device is running 23 or better
if (Build.VERSION.SDK_INT >= 23) {
ArrayList<StatusBarNotification> groupedNotifications = new ArrayList<>();
// step through all the active StatusBarNotifications and
for (StatusBarNotification sbn : getNotificationManagerService().getActiveNotifications()) {
// add any previously sent notifications with a group that matches our RemoteNotification
// and exclude any previously sent stack notifications
if (remoteNotification.getUserNotificationGroup() != null &&
remoteNotification.getUserNotificationGroup().equals(sbn.getNotification().getGroup()) &&
sbn.getId() != RemoteNotification.TYPE_STACK) {
groupedNotifications.add(sbn);
}
}
// since we assume the most recent notification was delivered just prior to calling this method,
// we check that previous notifications in the group include at least 2 notifications
if (groupedNotifications.size() > 1) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
// use convenience methods on our RemoteNotification wrapper to create a title
builder.setContentTitle(String.format("%s: %s", remoteNotification.getAppName(), remoteNotification.getErrorName()))
.setContentText(String.format("%d new activities", groupedNotifications.size()));
// for every previously sent notification that met our above requirements,
// add a new line containing its title to the inbox style notification extender
NotificationCompat.InboxStyle inbox = new NotificationCompat.InboxStyle();
{
for (StatusBarNotification activeSbn : groupedNotifications) {
String stackNotificationLine = (String)activeSbn.getNotification().extras.get(NotificationCompat.EXTRA_TITLE);
if (stackNotificationLine != null) {
inbox.addLine(stackNotificationLine);
}
}
// the summary text will appear at the bottom of the expanded stack notification
// we just display the same thing from above (don't forget to use string
// resource formats!)
inbox.setSummaryText(String.format("%d new activities", groupedNotifications.size()));
}
builder.setStyle(inbox);
// make sure that our group is set the same as our most recent RemoteNotification
// and choose to make it the group summary.
// when this option is set to true, all previously sent/active notifications
// in the same group will be hidden in favor of the notifcation we are creating
builder.setGroup(remoteNotification.getUserNotificationGroup())
.setGroupSummary(true);
// if the user taps the notification, it should disappear after firing its content intent
// and we set the priority to high to avoid Doze from delaying our notifications
builder.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH);
// create a unique PendingIntent using an integer request code.
final int requestCode = (int)System.currentTimeMillis() / 1000;
builder.setContentIntent(PendingIntent.getActivity(this, requestCode, DetailActivity.createIntent(this), PendingIntent.FLAG_ONE_SHOT));
Notification stackNotification = builder.build();
stackNotification.defaults = Notification.DEFAULT_ALL;
// finally, deliver the notification using the group identifier as the Tag
// and the TYPE_STACK which will cause any previously sent stack notifications
// for this group to be updated with the contents of this built summary notification
getNotificationManagerService().notify(remoteNotification.getUserNotificationGroup(), RemoteNotification.TYPE_STACK, stackNotification);
}
}
}
From https://developer.android.com/training/notify-user/group.
String GROUP_KEY_WORK_EMAIL = "com.android.example.WORK_EMAIL";
Notification newMessageNotification = new NotificationCompat.Builder(MainActivity.this, CHANNEL_ID)
.setSmallIcon(R.drawable.new_mail)
.setContentTitle(emailObject.getSenderName())
.setContentText(emailObject.getSubject())
.setLargeIcon(emailObject.getSenderAvatar())
.setGroup(GROUP_KEY_WORK_EMAIL)
.build();
By default, notifications are sorted according to when they were posted, but you can change order by calling setSortKey().
If alerts for a notification's group should be handled by a different notification, call setGroupAlertBehavior(). For example, if you want only the summary of your group to make noise, all children in the group should have the group alert behavior GROUP_ALERT_SUMMARY. The other options are GROUP_ALERT_ALL and GROUP_ALERT_CHILDREN.
Set a group summary
On Android 7.0 (API level 24) and higher, the system automatically builds a summary for your group using snippets of text from each notification. The user can expand this notification to see each separate notification, as shown in figure 1. To support older versions, which cannot show a nested group of notifications, you must create an extra notification that acts as the summary. This appears as the only notification and the system hides all the others. So this summary should include a snippet from all the other notifications, which the user can tap to open your app.
Note: The behavior of the group summary may vary on some device types such as wearables. To ensure the best experience on all devices and versions, always include a group summary when you create a group.
To add a group summary, proceed as follows:
Create a new notification with a description of the group—often best done with the inbox-style notification.
Add the summary notification to the group by calling setGroup().
Specify that it should be used as the group summary by calling setGroupSummary(true).
For example:
//use constant ID for notification used as group summary
int SUMMARY_ID = 0;
String GROUP_KEY_WORK_EMAIL = "com.android.example.WORK_EMAIL";
Notification newMessageNotification1 =
new NotificationCompat.Builder(MainActivity.this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notify_email_status)
.setContentTitle(emailObject1.getSummary())
.setContentText("You will not believe...")
.setGroup(GROUP_KEY_WORK_EMAIL)
.build();
Notification newMessageNotification2 =
new NotificationCompat.Builder(MainActivity.this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notify_email_status)
.setContentTitle(emailObject2.getSummary())
.setContentText("Please join us to celebrate the...")
.setGroup(GROUP_KEY_WORK_EMAIL)
.build();
Notification summaryNotification =
new NotificationCompat.Builder(MainActivity.this, CHANNEL_ID)
.setContentTitle(emailObject.getSummary())
//set content text to support devices running API level < 24
.setContentText("Two new messages")
.setSmallIcon(R.drawable.ic_notify_summary_status)
//build summary info into InboxStyle template
.setStyle(new NotificationCompat.InboxStyle()
.addLine("Alex Faarborg Check this out")
.addLine("Jeff Chang Launch Party")
.setBigContentTitle("2 new messages")
.setSummaryText("janedoe#example.com"))
//specify which group this notification belongs to
.setGroup(GROUP_KEY_WORK_EMAIL)
//set this notification as the summary for the group
.setGroupSummary(true)
.build();
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(emailNotificationId1, newMessageNotification1);
notificationManager.notify(emailNotificationId2, newMessageNotification2);
notificationManager.notify(SUMMARY_ID, summaryNotification);
The summary notification ID should stay the same so that it is only posted once, and so you can update it later if the summary information changes (subsequent additions to the group should result in updating the existing summary).
Use below give code for your notification manager and increment the count whenever a new notification received.
mNotificationManager.notify(count, mBuilder.build());

Notification in android Wear

I want to show a simple notification on android wear then i want to give a action on tap on notification,i don't want to show any paging in notification.
I seen many examples but all are of paging, i just want to give a simple notification and want to handle on tap event.
You have to change my resources to yours. setContentAction(0) is what you generally need.
public void showNotification() {
Intent eventIntent = new Intent(context, GridCardsActivity.class);
PendingIntent openAppIntent = PendingIntent.getActivity(context, 1, eventIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Action openAction = new Notification.Action(R.drawable.logo_sm, "open", openAppIntent);
Notification notification = new Notification.Builder(context)
.setContentTitle(pulse.getName())
.setContentText(pulse.getQuestion())
.setSmallIcon(R.drawable.logo)
.extend(new Notification.WearableExtender()
.addAction(openAction)
.setContentAction(0)
.setHintHideIcon(true)
.setBackground(bm)
)
.build();
((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE))
.notify((int) System.currentTimeMillis(), notification);
}

How can I create a Notification.Action and add it to a custom notification

I'm following Google's instructions here https://developer.android.com/training/wearables/notifications/creating.html
However, unsurprisingly, their code doesn't work. Specifically I'm trying to do this:
// Build the notification and add the action via WearableExtender
Notification notification =
new Notification.Builder(context)
.setSmallIcon(R.drawable.buzz_icon)
.setContentTitle("Buzz")
.setContentText("OpenBuzz")
.extend(new Notification.WearableExtender().addAction(action))
.build();
I want an action specific to the Wearable, so I have no choice but to use Notification.WearableExtender(). But it's addAction method only accepts an action as it's parameter. Here is my code for creating an action:
Notification.Action action =
Notification.Action.Builder(R.drawable.buzz_icon, actionIntent.toString(), pendingIntent);
Which doesn't work, as Android Studio says "Method call expected"
How can I successfully create a Notification.Action?
Or how else might I add a Wearable specific action to my notification?
You're on the right track.
You need to create a new NotificationCompat.Action.Builder and then call build() on it. Like this:
NotificationCompat.Action action =
new NotificationCompat.Action.Builder(android.R.drawable.ic_menu_call, "Only in wearable", pendingIntent)
.build();
Also, make sure that the action is defined as NotificationCompat.Action, not Notification.Action.
This example illustrates how to add a notification with an action (e.g. open the main activity).
NotificationCompat.Builde mBuilder = new NotificationCompat.Builder(this, null);
Intent myIntent = new Intent(this, MainActivity.class);
PendingIntent myPendingIntent = PendingIntent.getActivity(this, 0, myIntent, 0);
mBuilder.setContentTitle("Your_title")
.setContentText("Some_text")
.setSmallIcon(R.drawable.app_icon)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setOngoing(true)
.addAction(R.drawable.open_icon, "Open", myPendingIntent)
.setAutoCancel(false);
NotificationManager mNotifyManager = (NotificationManager) getApplicationContext().getSystemService(NOTIFICATION_SERVICE);
mNotifyManager.notify(1, mBuilder.build());

Android Wear Notification Page Actions

I have an app that kicks off a notification on a Wear device (the notification is created and shown on the Wear device).
What I want to do is have the "first" notification page display some high level info (app name, scroll to see more, etc...), and then have a list of pages containing content after that.
That works fine. The issue is that I want to attach an Action to each page (to kick off a PendingIntent). However, no matter what I try, I can't get the page to perform the Action.
I've tried:
setContentIntent
addAction
addAction and extend(new Notification.WearableExtender().setContentAction(0))
Anyone have any ideas?
I'm using Notification, not NotificationCompat, but I don't think that should make a difference.
UPDATE: I'm creating the notification on the watch. Here is the code I use:
private void createNotifications(ArrayList<Thing> things) {
DataApi data = Wearable.DataApi;
int notificationId = 0;
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification.Builder mainBuilder = new Notification.Builder(this)
.setSmallIcon(R.drawable.default_icon)
.setContentTitle("Things")
.setContentText("Swipe to see your things")
.setPriority(Notification.PRIORITY_DEFAULT);
List<Notification> pages = new ArrayList<>(things.size());
for(Thing thing : things) {
pages.add(createNotificationPageForThing(data, thing, notificationId).build());
notificationId++;
}
Notification n = new Notification.WearableExtender().addPages(pages).extend(mainBuilder).build();
nm.notify(notificationId, n);
}
private Notification.Builder createNotificationPageForThing(DataApi data, Thing thing, int notificationId) {
Asset bitmapAsset = getBitmapAsset(data, contact);
Intent thingIntent = new Intent(this, WearDetailActivity.class);
thingIntent.putExtra(WearDetailActivity.DETAIL_EXTRA, thing);
PendingIntent thingPendingIntent = PendingIntent.getActivity(this, notificationId, thingIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Action action = new Notification.Action(R.drawable.ic_action_social_person, "More details", thingPendingIntent);
Notification.Builder builder = new Notification.Builder(this)
.setSmallIcon(R.drawable.ic_action_social_person)
.setContentTitle(thing.getDisplayName())
.setPriority(Notification.PRIORITY_DEFAULT)
.addAction(action)
.extend(new Notification.WearableExtender().setContentAction(0));
if(bitmapAsset != null) {
try {
Bitmap b = BitmapFactory.decodeStream(
data.getFdForAsset(connection.getClient(), bitmapAsset).await().getInputStream());
builder.setLargeIcon(b);
} catch (Throwable ignore) {}
}
return builder;
}
#Eliezer, reading at the following line I did not understand what exactly is the behaviour you're experiencing ... explaining it in details might be helpful to debug your problem.
However, no matter what I try, I can't get the page to perform the Action.
Using .addAction() should work in your case. You'd want to use WearableExtender if you were creating the notification from the device, not the watch itself. Just to confirm something obvious - you're passing the .addAction a PendingIntent right?
Here's a code snippet from one of my applications, which accomplishes exactly what you're aiming for - I have just "Swipe for actions" text in the first page, and the next 2 pages perform different actions.
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
Intent openIntent = new Intent(this, CommonWearIntentService.class);
openIntent.setAction(CommonWearIntentService.ACTION_OPEN_ON_PHONE);
PendingIntent openPendingIntent = PendingIntent.getService(this, 0, openIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent addTransactionIntent = new Intent(this, CommonWearIntentService.class);
addTransactionIntent.setAction(CommonWearIntentService.ACTION_ADD_TRANSACTION);
PendingIntent addTransactionPendingIntent = PendingIntent.getService(this, 0, addTransactionIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(getString(R.string.app_name))
.setContentText(getString(R.string.swipe_for_actions))
.addAction(R.drawable.add_transaction, getString(R.string.add_transaction), addTransactionPendingIntent)
.addAction(R.drawable.common_full_open_on_phone, getString(R.string.common_open_on_phone), openPendingIntent)
.setVibrate(new long[]{500, 500, 500, 1000})
.setLights(Color.BLUE, 3000, 3000)
.setOngoing(true);
notificationManager.notify(ONGOING_NOTIFICATION_ID, builder.build());
Hope this helps!
Per the documentation, you must use NotificationCompat. After you switch to that setContentIntent() looks to be the right way to set the PendingIntent.
Example from the linked docs:
// Create builder for the main notification
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.new_message)
.setContentTitle("Page 1")
.setContentText("Short message")
.setContentIntent(viewPendingIntent);
// Create a big text style for the second page
BigTextStyle secondPageStyle = new NotificationCompat.BigTextStyle();
secondPageStyle.setBigContentTitle("Page 2")
.bigText("A lot of text...");
// Create second page notification
Notification secondPageNotification =
new NotificationCompat.Builder(this)
.setStyle(secondPageStyle)
.build();
// Add second page with wearable extender and extend the main notification
Notification twoPageNotification =
new WearableExtender()
.addPage(secondPageNotification)
.extend(notificationBuilder)
.build();
// Issue the notification
notificationManager =
NotificationManagerCompat.from(this);
notificationManager.notify(notificationId, twoPageNotification);

Android: Multiple Notifications as single list in Status Bar

I am trying to Notify user based on some criteria. Multiple Notifications are being shown in Status Bar but I want to Group the notification in single notification and when user clicks in the Status Bar, I want to retrieve all notifications in that group. Is that possible? Or I have to maintain PendingIntents of those notifications? Any help will be appreciated. For example, if birthdays of two friends come on same day, then 2 notifications should be shown. I want to combine these notifications i.e. instead of 2 notifications in the status bar, I want one, when user clicks on it, it should have information about 2 notifications. Is it possible?
Please see the code below for displaying notifications.
public void displayNotification(BirthdayDetail detail)
{
NotificationCompat.Builder builder = new NotificationCompat.Builder(this.context);
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setContentTitle(detail.getContactName());
builder.setContentText(detail.getContactBirthDate());
Intent resultIntent = new Intent(this.context, NotificationView.class);
resultIntent.putExtra("name", detail.getContactName());
resultIntent.putExtra("birthdate", detail.getContactBDate());
resultIntent.putExtra("picture_path", detail.getPicturePath());
resultIntent.putExtra("isContact", detail.isFromContact());
resultIntent.putExtra("notificationId", notificationId);
if(detail.isFromContact())
{
resultIntent.putExtra("phone_number", detail.getPhoneNumber());
}
PendingIntent resultPendingIntent = PendingIntent.getActivity(this.context, requestCode++,
resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(resultPendingIntent);
notificationManager
= (NotificationManager) this.context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notificationId, builder.build());
notificationId++;
}
When you need to issue a notification multiple times for the same type
of event, you should avoid making a completely new notification.
Instead, you should consider updating a previous notification, either
by changing some of its values or by adding to it, or both.
You can use something like:
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());
Source: http://developer.android.com/training/notify-user/managing.html

Categories

Resources