Xamarin.Forms Android Local Notification Not Sending - android

I have followed the Xamarin walkthrough, and it's not working for me.
The code falls through this cleanly, but it never sends the notification.
It never shows up on my emulator or device.
I have no idea what is going on.
public override void OnReceive(Context context, Intent intent)
{
string message = intent.GetStringExtra("message");
string title = intent.GetStringExtra("title");
int id = int.Parse(intent.GetStringExtra("id"));
//Generate a notification with just short text and small icon
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.SetAutoCancel(true) // Dismiss from the notif. area when clicked
.SetContentTitle(title) // Set its title
.SetContentText(message); // The message to display.
NotificationManager notificationManager = (NotificationManager)context.GetSystemService(Context.NotificationService);
notificationManager.Notify(id, builder.Build());
Any help or links would be very helpful. I'm just completely lost; been working on this for about 14 hours now, and cannot find any help on the Google.
Answer to my inquiry: You must have an Icon set for notifications to be properly build and sent. Though, it won't send an error for not having one.
Short version: Needed to add
.SetSmallIcon(Resource.Drawable.icon);

Add an icon to notification.
Notification.Builder builder = new Notification.Builder (this)
.SetContentTitle ("Title")
.SetContentText ("Message")
.SetSmallIcon (Resource.Drawable.ic_notification);
Notification notification = builder.Build();
NotificationManager notificationManager =
GetSystemService (Context.NotificationService) as NotificationManager;
const int notificationId = 0;
notificationManager.Notify (notificationId, notification);

Related

Is there any Android notifications setContentTitle and setContextText magic values?

I'm currently working on a library with android support.
I'm being asked to notify user on foreground service start.
The notification must contain "ApplicationName" as title, and "ApplicationName is running" as text. The notification icon has to be the same as the launcher one.
The target API level is 26.
The notification did not work because the previous developper forgot to open the notification chanel. This is now fixed, we have the notification that pops correctly. And the label are matching expectation.
But now i'm questioning why the notification contains the expected values. I could not find any reference in the javadoc.
The following code will display the notification as expectecd the application's name as title and the text "ApplicationName is running" :
#Override
public void onCreate() {
NotificationChannel channel = new NotificationChannel("APPLICATION_CHANNEL", "MyService", NotificationManager.IMPORTANCE_LOW);
channel.setDescription(notificationChannelText);
//block below useful for head up notification
channel.setSound(null, null);
channel.setShowBadge(false);
channel.enableLights(false);
channel.enableVibration(false);
NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
}
#Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
foregroundNotification();
return Service.START_STICKY;
}
/**
* In order to start foreground service we and generate a service running notification.
*/
private void foregroundNotification() {
Context context = getApplicationContext();
Intent notificationIntent = new Intent(context, getClass());
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
Notification notification = new Notification.Builder(context, "APPLICATION_CHANNEL")
.setContentTitle("Title")
.setContentText("Subject")
.setContentIntent(pendingIntent)
.build();
startForeground(42666, notification);
}
Why doesn't it just display a notification with "Title" as the title and "Subject" as content ?
Are there any constants or magic values that we have to know ?
Where can we find any documentation or definition about it ?
Edit 2020/04/01 : Added code representing notification channel creation
I found your problem. This is result of your code:
and after add small icon:
.setSmallIcon(R.mipmap.ic_launcher)
It works fine

Heads up with reply (RemoteInput) does not cancel notification

Step1 : Build Notification with Reply intent and heads up notification
private void buildInlineReplyNotification() {
// Create an instance of RemoteInput.Builder that you can add to your notification action.
// This class's constructor accepts a string that the system uses as the key for the text input.
// Later, your handheld app uses that key to retrieve the text of the input.
RemoteInput remoteInput = new RemoteInput.Builder(KEY_TEXT_REPLY).setLabel(
getResources().getString(R.string.reply_label)).build();
// Attach the RemoteInput object to an action using addRemoteInput().
NotificationCompat.Action compatAction =
new NotificationCompat.Action.Builder(R.mipmap.ic_reply,
getResources().getString(R.string.reply), replyPendingIntent).addRemoteInput(
remoteInput).setAllowGeneratedReplies(true).build();
// Build the notification and add the action.
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this).setSmallIcon(R.mipmap.ic_notification)
.setContentTitle(
getResources().getString(R.string.notification_created) + mNotificationId)
.setContentText(getResources().getString(R.string.type_reply))
.setShowWhen(true)
.addAction(compatAction);
mBuilder.setPriority(Notification.PRIORITY_HIGH).setVibrate(new long[0]);
// Issue the notification.
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(mNotificationId, mBuilder.build());
}
Step2 : cancel after reply from notification
private void updateNotification(Context context, int notifyId) {
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
NotificationCompat.Builder builder =
new NotificationCompat.Builder(context).setSmallIcon(R.mipmap.ic_notification)
.setContentText(context.getString(R.string.message_sent));
notificationManager.cancel(notifyId);
}
Issues is not cancel notification by notificationManager.cancel(notifyId) but if i remove this mBuilder.setPriority(Notification.PRIORITY_HIGH).setVibrate(new long[0]); Than work perfect so, what is issue with priority in notification ?

What the purpose of setGroup() in Notification.Builder?

I have a some troubles with understanding of goal of setGroup() method.
As docs said :
...Grouped notifications may display in a cluster or stack on devices which support such rendering....
Here it is the first question :
What it is this rendering? What's so special about it?!
I create a method which show a custom text message :
public static void showNotification(Context context, String title, String message, PendingIntent pendingIntent) {
notificationMessages.add(message);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
// .setGroupSummary(true)
.setSmallIcon(R.drawable.ic_launcher)
.setContentInfo("" + (notificationMessages.size()))
/*.setGroup(++i + "")*/;
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
inboxStyle.setBigContentTitle(title);
for (int i = 0; i < notificationMessages.size(); i++) {
inboxStyle.addLine(notificationMessages.get(i));
}
builder.setContentIntent(pendingIntent);
builder.setStyle(inboxStyle);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = builder.build();
mNotificationManager.notify(0, notification);
}
and play with notificationID, setGroup and setGroupSummary methods.
public static void showNotification(Context context, String title, String message, PendingIntent pendingIntent) {
notificationMessages.add(message);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
// .setGroupSummary(true)
.setSmallIcon(R.drawable.ic_launcher)
.setContentInfo("" + (notificationMessages.size()))
.setGroup(GROUP_KEY);
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
inboxStyle.setBigContentTitle(title);
for (int i = 0; i < notificationMessages.size(); i++) {
inboxStyle.addLine(notificationMessages.get(i));
}
builder.setContentIntent(pendingIntent);
builder.setStyle(inboxStyle);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = builder.build();
mNotificationManager.notify(new Random().nextInt(3), notification);
}
But, no visual changes
comes if I commented lines or not. So here is a stuck for me in understanding of purpose of this method.
from the official docs:
http://developer.android.com/preview/features/notification-updates.html
Android N also allows you to bundle similar notifications to appear as a single notification. To make this possible, Android N uses the existing NotificationCompat.Builder.setGroup() method. Users can expand each of the notifications, and perform actions such as reply and dismiss on each of the notifications, individually from the notification shade.
Meaning the setGroup will only make a difference if the device supports it.
Devices that support it are:
Android Wear devices. when showing remote notifications, you can group together them
Android N. Devices running the Android N developer preview (or in the future the official N release), will show a group of notifications together
The following blog post shows how those work on Android N: https://medium.com/exploring-android/android-n-introducing-upgraded-notifications-d4dd98a7ca92
bellow is a render of that a group looks like:
That means that setGroup will make no difference on devices running anything bellow API23, that includes, Marshamallow, Lollipop, KitKat, etc.
setGroupSummaryis there to support grouped notifications on devices before Nougat. It replaces the single notifications with 1 summary notification.
On Nougat+ the system creates a normal group, which is not your notification with setGroupSummary(true)

How to group android notifications like whatsapp?

I donĀ“t know how to group two or more notifications into only one and show a message like "You have two new messages".
Steps to be taken care from the below code.
NotificationCompat.Builder:contains the UI specification and action information
NotificationCompat.Builder.build() :used to create notification (Which returns Notification object)
Notification.InboxStyle: used to group the notifications belongs to same ID
NotificationManager.notify():to issue the notification.
Use the below code to create notification and group it. Include the function in a button click.
private final int NOTIFICATION_ID = 237;
private static int value = 0;
Notification.InboxStyle inboxStyle = new Notification.InboxStyle();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.push_notify_icon);
public void buttonClicked(View v)
{
value ++;
if(v.getId() == R.id.btnCreateNotify){
NotificationManager nManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(this);
builder.setContentTitle("Lanes");
builder.setContentText("Notification from Lanes"+value);
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setLargeIcon(bitmap);
builder.setAutoCancel(true);
inboxStyle.setBigContentTitle("Enter Content Text");
inboxStyle.addLine("hi events "+value);
builder.setStyle(inboxStyle);
nManager.notify("App Name",NOTIFICATION_ID,builder.build());
}
}
For separate notifications assign different NOTIFICATION_IDs..
For full logic please consider checking my answer.I used the logic with shared preferences and broadcast receiver as i needed to group each user message into single one and be in sight of active notifications.As only by targeting the api level 23 you can get active notifications,it did not help me at all.So i decided to write some slight logic.Check it here if you feel like to.
https://stackoverflow.com/a/38079241/6466619
You need to create the notification so that it can be updated with a notification ID by calling NotificationManager.notify(ID, notification).
The following steps need to be created to update the notification:
Update or create a NotificationCompat.Builder object
Build a Notification object from it
Issue the Notification with the same ID you used previously
An example taken from the android developer docs:
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());
...
Also see the Android docs on Stacking Notifications
https://developer.android.com/training/wearables/notifications/stacks.html
You can stack all your notifications into a single group using the setGroup method and passing your groupId string as parameter.
builer.setGroup("GROUP ID STRING" ) ;
NotificationManager nManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(this);
builder.setContentTitle("Lanes");
builder.setGroup("GROUP_ID_STRING");
builder.setContentText("Notification from Lanes"+value);
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setLargeIcon(bitmap);
builder.setAutoCancel(true);
inboxStyle.setBigContentTitle("Enter Content Text");
inboxStyle.addLine("hi events "+value);
builder.setStyle(inboxStyle);
nManager.notify("App Name",NOTIFICATION_ID,builder.build());

When a new notification comes the title and text of old notification gets cleared in android

I am creating an application with a notification at different times. First notification display fine in the notification bar with an icon, title and text. But when the second notification comes the title and text of the first notification gets cleared and the second one displays. For the third notification again the second one's title and text gets cleared and so on.
The code i am using is
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
long mNotificationId = System.currentTimeMillis();
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setSound(uri);
NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
bigTextStyle.setBigContentTitle("Time to Sleep!!!");
bigTextStyle.bigText("A good laugh and a long sleep are the best cures in the doctor's book.");
mBuilder.setStyle(bigTextStyle);
mBuilder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL;
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mNotifyMgr.notify((int)mNotificationId, mBuilder.build());
Any help would be appreciated. Thanks in advance.
I think you are only setting text for BigTextStyle
Also set Values for small or default settings
for eg
// Small - default style
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setDefaults(Notification.DEFAULT_ALL)
.setSmallIcon(context.getApplicationInfo().icon)
.setWhen(System.currentTimeMillis())
.setContentTitle(extras.getString("title"))
.setTicker(extras.getString("title"))
.setContentIntent(contentIntent);
Just check the mNotificationId value if its same
If same you can use the following to generate the random number
Random random = new Random();
int m = random.nextInt(9999 - 1000) + 1000;
and then use this m
mNotifyMgr.notify(m, mBuilder.build());
Try using
int notification_id = (int) date.getTime();
to ensure that every time a unique id is generated. Notifications with unique ids do not get over written and you can see multiple notifications in the notification panel. Hope this helps.

Categories

Resources