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.
Related
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.
How can I switch all these settings on programmatically?
I noticed when you install WhatsApp they are all switched on in the beginning(look at the image below).
But I can not find a way to turn them on programmatically.
Here is how I send notifications:
private void sendNotification(Intent intent){
Context context = NotificationService.this;
//open the activity after the notification is clicked
Intent intent1 = new Intent(getApplicationContext(),MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent1, 0);
Notification.Builder builder = new Notification.Builder(context)
.setTicker("Notification")
.setContentTitle("Important Message")
.setContentText("This is an example of a push notification using a Navigation Manager")
.setSmallIcon(R.drawable.ic_add)
.setContentIntent(pIntent);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
//These are necessary for the notification to pop up
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O){
builder.setPriority(Notification.PRIORITY_MAX);
builder.setSound(alarmSound);
builder.setLights(Color.BLUE, 500, 500);
}
//after android O we must use notification channels
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
String channelId = "Your_channel_id";
NotificationChannel channel = new NotificationChannel(
channelId,
"Reminder to remind to review your notes",
NotificationManager.IMPORTANCE_HIGH);
if(alarmSound != null){
AudioAttributes att = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build();
channel.setSound(alarmSound,att);
}
channel.setLightColor(Color.BLUE);
channel.enableVibration(true);
channel.setDescription("Hello Dear friends"); //this is to test what this is
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
channel.setVibrationPattern(new long[]{300, 300, 300});
notificationManager.createNotificationChannel(channel);
builder.setChannelId(channelId);
}
Notification notification = builder.build();
notificationManager.notify(0, notification);
}
I also added this permission to manifest:
<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />
Update:
Using this code on the emulator, I get the heads-up notification. But on my Xiaomi device, there is no heads-up notification. It just appears on the status bar. If I manually turn on the floating notification (which you can see in the photo) then I will get heads-up notification. But they are switched off by default. When you install Whatsapp they are all switched on.
Is that a kind of privilege for Whatsapp as it is famout? or is there a way to do it?
By default, when you install a app, the system register's default notification channel (on low priority) that doesn't support head up notification by default, it's turned off. You can't control that.
But what you can do it create your own notification channel with highest priority and then register it on app run once.
After that just pass the channel Id with your notification builder so that system shows the head's up notification which you want.
More information can be found here https://developer.android.com/training/notify-user/channels
I have tried for this but unable to set these settings programmatically. Instead of this I have used following method to open notification settings screen to enable notification sounds/vibration.
private void openNotificationSettingsForApp(String channelId) {
// Links to this app's notification settings.
Intent intent = new Intent();
intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && channelId!=null){
intent.setAction(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
intent.putExtra(Settings.EXTRA_CHANNEL_ID,channelId);
intent.putExtra("android.provider.extra.APP_PACKAGE", getPackageName());
}
intent.putExtra("app_package", getPackageName());
intent.putExtra("app_uid", getApplicationInfo().uid);
startActivity(intent);
}
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
for some reason when I make a notification appear on my app in will vibrate and make noise but no banner appears across the top of the phone. Is there a specific command I need to make it do this?
public Notification getNotification(String message) {
Intent intent = new Intent(serviceContext, NotificationGenerator.class); //not sure how
// this class i pass matters
PendingIntent pi = PendingIntent.getActivity(serviceContext, 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(serviceContext)
.setContentTitle(message)
.setContentText(message)
.setSmallIcon(R.drawable.dominos_icon)
.setContentIntent(pi);
Notification n = builder.build();
n.defaults = Notification.DEFAULT_ALL;
return n;
}
Your code will work fine once you will add the lines below:
NotificationManager n_mngr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
n_mngr.notify(NOTIF_ID, n);
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.