Android push notification opening a custom page - android

my question for you is the following: I have a web app written in HTML5, wrapped as a native Android app in order to use Google Push Notifications. Because my app is using many notifications for different reasons, I want to be able to say each time a notification is received, which page to be open, like adding a 'href' in the notification intent. Is this possible?
If I wasn't clear enough please let me know.
Thanks

You can define your own notification message content. The Message builder from Google supports key value pairs to be set by the sender of the notification.
See http://developer.android.com/reference/com/google/android/gcm/server/Message.html
Example:
Message message = new Message.Builder()
.addData("link1", "http://mypage1.com")
.addData("link2", "http://mypage2.com")
.build();

When you create the notification, use setContentIntent() to attach an Intent that has been constructed to visit the right webpage:
// assuming <this> is an Activity or other Context
Intent urlIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(yourUrl));
PendingIntent urlPendingIntent = PendingIntent.getActivity(this, 0 urlIntent, 0);
Notification.Builder b = new Notification.Builder(this)
.setSmallIcon(...).setContentTitle(...).setContentText(...) // etc.
.setContentIntent(urlPendingIntent);
NotificationManager noMan
= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
noMan.notify(ID, b.build());
If you expect to have more than one of these in the notification panel at a time:
Reconsider. It's spammy to post more than one notification.
If you must, you'll need a separate ID (or separate tag) for each.

Related

How to implement Android Bubbles notifications on Android 11(Api 30)+

I am trying to implement the Android Bubbles notifications API but it's not working for me, it's displaying as an ordinary notification. I am testing on emulator API 30(Android 11). I got the people-example working on the device, and I am following the Conversation Notifications guidelines.
The notification uses MessagingStyle.
(Only if the app targets Android 11 or higher) The notification is associated with a valid long-lived dynamic or cached sharing shortcut.
The notification can set this association by calling setShortcutId()
or setShortcutInfo(). If the app targets Android 10 or lower, the
notification doesn't have to be associated with a shortcut, as
discussed in the fallback options section.
The user hasn't demoted the conversation from the conversation section via notification channel settings, at the time of posting.
Please tell me what did I missed?
Also, I got a few optional questions about the design of Bubbles.
At what point of the app should I create the shortcuts and when to update it?
How the Person object needs to be cached?
This is what I got so far
Recipient recipient = ...; // Sender data
Message message = ...; // Message data
Intent intent = new Intent(context, ChatActivity.class);
intent.putExtra(ChatActivity.CONVERSATION_ID, message.conversationId);
PendingIntent bubbleIntent =
PendingIntent.getActivity(context, 0, intent, 0);
IconCompat icon = loadIcon(recipient);
Person person = loadPerson(recipient, icon);
NotificationCompat.MessagingStyle style = getMessagingStyle(person);
createOrVerifyChannel();
Notification notification = new NotificationCompat.Builder(context, CHANNEL_ID)
.setContentTitle(getNewMessagesCount(message) + " new messages with " + person.getName())
.setCategory(Notification.CATEGORY_MESSAGE)
.setContentText(message.text)
.setBubbleMetadata(
new NotificationCompat.BubbleMetadata.Builder()
.setDesiredHeight(600)
.setIntent(bubbleIntent)
.setAutoExpandBubble(true)
.setSuppressNotification(true)
.setIcon(icon)
.build()
)
.addPerson(person)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setWhen(message.date)
.setStyle(style)
.setShortcutInfo(
new ShortcutInfoCompat.Builder(context, message.conversationId + "")
.setActivity(new ComponentName(context, ChatActivity.class))
.setCategories(new HashSet<>(Collections.singletonList(Notification.CATEGORY_MESSAGE)))
.setIcon(icon)
.setPerson(person)
.setRank(0)
.setShortLabel(person.getName())
.setIntent(intent)
.build()
)
.build();
NotificationManagerCompat.from(context).notify(message.id + "," + message.type,
message.id, notification);
Manifest
<activity
android:name=".screens.chat.ChatActivity"
android:allowEmbedded="true"
android:resizeableActivity="true"
tools:targetApi="n" />
Gradle
targetSDKVersion 30
implementation 'androidx.appcompat:appcompat:1.3.0-alpha02'
The one thing that I missed was adding .setLongLived(true) for the ShortcutInfoCompat. It solves the problem.
I learned that it best to manage the ShortcutInfo on the app level since you can have at most 5 at a time, so there is no harm caching those in memory, it includes the Person object as well.
Also, you should add LocusId for the NotificationCompat, this id is shared among shortcuts, notifications, and views. To add it to the views you need to put in some extra work, as described in ContentCaptureManager

How to prevent android quick reply notification from being stuck in loading?

My app uses the Android N's new quick-reply feature to quickly take notes from a fixed notification, without having the user to open an activity.
However, I would like the notification to be reset to its initial state after the user sends the quick reply message, without having to dismiss the notification.
Here is my code:
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? createChannel() : "").setSmallIcon(android.R.mipmap.sym_def_app_icon).setContentTitle("My Awesome App").setContentText("Doing some work...").setContentIntent(pendingIntent);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
android.support.v4.app.RemoteInput remoteInput = new RemoteInput.Builder(BookmarkCreatorReceiver.TXT_REPLY).setLabel("Reply").build();
Intent replyIntent = new Intent(this, BookmarkCreatorReceiver.class);
PendingIntent replyPendingIntent = PendingIntent.getBroadcast(this, 0, replyIntent, 0);
NotificationCompat.Action action = new NotificationCompat.Action.Builder(android.R.drawable.ic_dialog_email, "Bookmark", replyPendingIntent).addRemoteInput(remoteInput).build();
NotificationCompat.Action actionQuick = new NotificationCompat.Action.Builder(android.R.drawable.ic_dialog_email, "Quick", replyPendingIntent).build();
builder.addAction(action);
builder.addAction(actionQuick);
}
startForeground(NOTIFICATION_ID, builder.build());
The problem is that once the user sends a message and the Broadcast receiver is called, the notification stays in the loading state like this:
How can I remove the loading message, without having to discard the notification?
Per the Notifications in Android N blog post:
After you’ve processed the text, you must update the notification by calling notify() with the same id and tag (if used). This is the trigger which hides the Direct Reply UI and should be used as a technique to confirm to the user that their reply was received and processed correctly.
Also note:
For most templates, this should involve using the new setRemoteInputHistory() method which appends the reply to the bottom of the notification.
This ensures that users see the text they entered was properly handled.

notifications not getting grouped

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!!

Get response after Android Wear Action

I'm trying to develop with Android Wear. I tried all the tutorial provided in the documentation, but now I want to try to do something smarter. I'm trying to get back the text that user says (with emulator written by computer keyboard), so I made it with this code:
protected void voiceNotification() {
// Crete intent for the response action
Intent replyIntent = new Intent(this, ReplyActivity.class);
// Adding intent to pending intent
PendingIntent replyPendingIntent = PendingIntent.getActivity(this, 0,
replyIntent, 0);
// Build the notification
NotificationCompat.Builder replyNotificationBuilder = new NotificationCompat.Builder(
this);
replyNotificationBuilder
.setSmallIcon(android.R.drawable.ic_btn_speak_now);
replyNotificationBuilder.setContentTitle("Messaggio");
replyNotificationBuilder.setContentText("Testo del messaggio");
replyNotificationBuilder.setContentIntent(replyPendingIntent);
replyNotificationBuilder.setNumber(++numMessages);
replyNotificationBuilder.setAutoCancel(true);
replyNotificationBuilder.setSound(RingtoneManager
.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
replyNotificationBuilder.setVibrate(new long[] { 1000, 1000 });
replyNotificationBuilder.setTicker("Hai una nuova notifica!");
// Create remote input
RemoteInput remoteInput = new RemoteInput.Builder(EXTRA_VOICE_REPLY)
.setLabel(getResources().getString(R.string.reply_label))
.build();
// Create the wearable notification
Notification replyNotification = new WearableNotifications.Builder(replyNotificationBuilder)
.addRemoteInputForContentIntent(remoteInput)
.build();
// Get the instance of NotificationManagerCompat and send my notification
NotificationManagerCompat.from(this).notify(0, replyNotification);
}
With this code on the emulator I'm getting 2 views: one with the text of my notification and a second one in which I can answer to notification with voice (keyboard with emulator). It's working all good, but I want to know if it's possible to get the text I said (wrote with emulator) to do something in my application (I saw on the emulator display that after I said/wrote somethings it appears 2 button "Edit" and "Send", so I think that with button "Send" I can get the text in my application to do something). I try to find out something in the documentation, but I don't find nothing. I hope you can help me to get this text.
You'll need to implement a Broadcast-receiver that listens to the pendingIntent you defined - the reply from the user will be passed in an extra string you defined in the RemoteInput - in your case this would be EXTRA_VOICE_REPLY.
You might want to have a look at these two files someone posted on GitHub in order to understand what is going on.
http://git.io/emKcrw
http://git.io/_PRW_w

How to give counter if more than one Notifications are there

I have implemented PushNotification Using C2dm. I am getting notification from c2dm also. My problem is I want to give a counter when I get more than one notifications, I mean like "You have a Notification(count)". How can I implement this.
you can do to set the number value into the Notification object
Notification notifyDetails = new Notification(R.drawable.alarm,intent.getExtras().getString(KEY_TITLE),System.currentTimeMillis());
notifyDetails.number = 1; ////// here you can pass the counter value which will so you the number
here is the link
http://developer.android.com/reference/android/app/Notification.html#number
http://developer.android.com/guide/topics/ui/notifiers/notifications.html
Android Notification Bar Number
Are you looking for Notification#number?
NotificationManager notificationManager =(NotificationManager)context.getSystemService(NOTIFICATION_SERVICE);
notification.setNumber(1);
NotificationManager notificationManager=(NotificationManager)context.getSystemService(NOTIFICATION_SERVICE);
This creates the notificationManager class instance. Then you will have notification object with which you can do any adjustment. To set the number of the messages you have received, simply set this:
notification.setNumber(1);

Categories

Resources