Local Notifications are not showing in API 27 - xamarin.forms

Notifications are working for Api 26 and below perfectly but they are not working with API 27.
Here is my code for create notification channel:
private void CreateNotificationChannel()
{
try
{
if (Build.VERSION.SdkInt < BuildVersionCodes.O)
{
return;
}
var notificationManager = (NotificationManager)GetSystemService(NotificationService);
NotificationChannel mChannel = notifManager.GetNotificationChannel("1");
if (mChannel == null)
{
mChannel = new NotificationChannel("1", "Chat Application", Android.App.NotificationImportance.High);
mChannel.EnableVibration(true);
mChannel.SetVibrationPattern(new long[] { 100, 200, 300, 400, 500, 400, 300, 200, 400 });
notifManager.CreateNotificationChannel(mChannel);
}
}
catch (Exception exception)
{
LoggingManager.Error(exception);
}
}
And my notification Service is:
var activity = Forms.Context as Activity;
Intent intent = new Intent(activity, typeof(MainActivity));
intent.AddFlags(ActivityFlags.ClearTop);
Random random = new Random();
int pushCount = random.Next(9999 - 1000) + 1000; //for multiplepushnotifications
intent.AddFlags(ActivityFlags.ClearTop);
var pendingIntent = PendingIntent.GetActivity(activity, pushCount, intent, PendingIntentFlags.Immutable);
// Instantiate the builder and set notification elements:
NotificationCompat.Builder builder = new NotificationCompat.Builder(Forms.Context,"1")
.SetContentTitle(messageTitle)
.SetDefaults(1|2)
.SetContentText(Message)
.SetContentIntent(pendingIntent)
.SetAutoCancel(true)
.SetChannelId("1")
.SetPriority(1);
builder.SetSmallIcon(Resource.Drawable.icon);
// Build the notification:
Notification notification = builder.Build();
// Get the notification manager:
NotificationManager notificationManager = Forms.Context.GetSystemService(Context.NotificationService) as NotificationManager;
// Publish the notification:
notificationManager.Notify(5, notification);
Please help me out or give me some suggestions how can I resolve this issue.

I have a feeling there is something wrong with your channel creation, below you can check my working piece of code.
var mChannel = new NotificationChannel(CHANNEL_ID, "Chat Application", Android.App.NotificationImportance.High)
{
Description = "Firebase Cloud Messages appear in this channel"
};
mChannel.EnableVibration(true);
mChannel.SetVibrationPattern(new long[] { 100, 200, 300, 400, 500, 400, 300, 200, 400 });
var notificationManager = (NotificationManager) GetSystemService(NotificationService);
notificationManager.CreateNotificationChannel(channel);

Can you please try with
notificationManager.Notify(new Random().Next(), notification);
instead of
notificationManager.Notify(5, notification);

Related

Xamarin.Forms Push Notification Payload in Android

Hi I have a push notification handler in my Android project. My goal is to have a different payload for each notification.
The problem is when I received notifications
and tap on a notification I want, the payload I get is usually the very first notification arrived. So for example from my screenshot, I tapped on notification with qHzkeyRp~~~~~: 2 I get the payload from Jayson Pogi: 1 notification. Other scenario is when I tapped on the first notification arrived, other notifications doesn't have payload.
Here's my code just incase
public void CreateLocalNotificaiton(string title, string body, string payload, int notifId, string groupName, bool hasIntent = false)
{
//var notificationBuilder = new NotificationCompat.Builder(this, AppConstants.NotificationChannelName)
// .SetContentTitle(title)
// .SetSmallIcon(Resource.Drawable.appicon)
// .SetContentText(body)
// .SetPriority(1)
// .SetVisibility((int)NotificationVisibility.Public)
// .SetChannelId(AppConstants.NotificationChannelId)
// .SetAutoCancel(true)
// .SetGroup("com.pordiva.omnigoo.businessmobile.OmniGoo")
// .SetShowWhen(false)
// ;
var notificationBuilder = new NotificationCompat.Builder(this, AppConstants.NotificationChannelName)
.SetContentTitle(title)
.SetSmallIcon(Resource.Drawable.appicon)
.SetContentText(body)
.SetPriority(PRIORITY_DEFAULT)
.SetChannelId(AppConstants.NotificationChannelId)
.SetAutoCancel(true)
//.SetGroupSummary(true)
//.SetGroup("com.pordiva.omnigoo.businessmobile." + groupName)
;
if (hasIntent)
{
var intent = new Intent(this, typeof(MainActivity));
intent.AddFlags(ActivityFlags.NewTask | ActivityFlags.SingleTop);
// add extra data so we can retreive this
if (payload != null)
{
Bundle bundle = new Bundle();
bundle.PutString("payload", payload);
intent.PutExtras(bundle);
}
var pendingIntent = PendingIntent.GetActivity(
this,
0,
intent,
PendingIntentFlags.OneShot);
notificationBuilder.SetContentIntent(pendingIntent);
}
var notificationManager = GetSystemService(Context.NotificationService) as NotificationManager; // NotificationManager.FromContext(CrossCurrentActivity.Current.AppContext);
if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
{
NotificationImportance importance = global::Android.App.NotificationImportance.High;
NotificationChannel notificationChannel = new NotificationChannel(AppConstants.NotificationChannelId, title, importance);
notificationChannel.EnableLights(true);
notificationChannel.EnableVibration(true);
notificationChannel.SetShowBadge(true);
notificationChannel.Importance = NotificationImportance.High;
notificationChannel.SetVibrationPattern(new long[] { 100, 200, 300, 400, 500, 400, 300, 200, 400 });
if (notificationManager != null)
{
notificationBuilder.SetChannelId(AppConstants.NotificationChannelId);
notificationManager.CreateNotificationChannel(notificationChannel);
}
}
notificationManager.Notify(notifId, notificationBuilder.Build());
}
SOLVED
Must have unique value in PendingIntent.GetActivity requestCode parameter
SOLVED ✌💪
Must have unique value in PendingIntent.GetActivity requestCode parameter

Custom sound for NotificationChannel for Android 11 not working

I have push notifications with custom sounds working until android 10. Since Android 11 the sound attached to the notification channel stopped playing when the notification is presented as drop down style. It works when it is presented as full screen activity.
Here is the example source code how the notification channel is created
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelId = "media_playback_channel_v_01_1_sound"
String channelName = "Channel High"
NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
channel.setDescription("My custom sound");
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
AudioAttributes.Builder builder = new AudioAttributes.Builder();
builder.setUsage(AudioAttributes.USAGE_NOTIFICATION);
String basePath = ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/" + R.raw.alarm_sound);
Uri alarmSound = Uri.parse(basePath);
channel.setSound(alarmSound, builder.build());
channel.enableVibration(true);
channel.enableLights(true);
channel.setLightColor(Color.RED);
}
}
I use the notification channel above and fire the notification as follow:
private void fireNotification(Context context) {
String channelId = "media_playback_channel_v_01_1_sound"
NotificationChannel channel = getManager().getNotificationChannel(channelId);
PendingIntent fullScreenPendingIntent = PendingIntent.getActivity(context, 100,
fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT);
String contentText = getString(R.string.call_notification_incoming_from, from);
Bundle args = new Bundle();
args.putInt(CallActivity.INTENT_CALL_NOTIFICATION_ID, ActiveCall.ANDROID_10_PUSH_CALL_NTFN_ID);
args.putBoolean(CallActivity.INTENT_FROM_CALL_NOTIFICATION, true);
args.putString(CallActivity.INTENT_NOTIFICATION_CALL_ID, fullScreenIntent.getStringExtra(CallActivity.INTENT_NOTIFICATION_CALL_ID));
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, type)
.setSmallIcon(iconRes)
.setContentTitle(getString(R.string.app_name))
.setContentText(contentText)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_CALL)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setOngoing(true)
.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_ALL)
.setTimeoutAfter(Consts.MINUTE)
.addExtras(args);
notificationBuilder.addAction(
R.drawable.ic_accept_call,
getString(R.string.call_notification_incoming_answer),
answerPendingIntent);
notificationBuilder.addAction(
R.drawable.ic_decline_bttn,
getString(R.string.call_notification_incoming_reject),
rejectPendingIntent
);
notificationBuilder.setFullScreenIntent(fullScreenPendingIntent, true);
// Build
Notification notification = notificationBuilder.build();
notification.sound = notificationSoundUri;
notification.flags |= (Notification.FLAG_SHOW_LIGHTS | Notification.FLAG_INSISTENT Notification.FLAG_NO_CLEAR);
notification.ledARGB = Color.RED;
notification.ledOnMS = 300;
notification.ledOffMS = 1000;
// Notify
NotificationManager notificationManager = getManager();
notificationManager.notify(id, notification);
}
Note that the same code plays the sound in Android 10, while it does not on Android 11.
I am also stuck for android 11 but I tried different channel name and do not channel channel ID.
This solution is working for me in every android version 11 devices.
Please try this and let me know if this will not working for you.
public void showNotification(String title, String message) {
count++;
Intent intent = new Intent(this, HomePageActivity.class);
String channel_id = "notification_channel";
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getApplicationContext().getPackageName() + "/" + R.raw.coin);
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), channel_id)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setAutoCancel(true)
.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000})
.setOnlyAlertOnce(true)
.setSound(soundUri)
.setContentIntent(pendingIntent);
builder.setNumber(count);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
builder = builder.setContent(getCustomDesign(title, message));
} else {
builder = builder.setContentTitle(title).setContentText(message).setSmallIcon(R.mipmap.ic_launcher_round);
}
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(channel_id, "DIFFRENT_CHANNEL_NAME", NotificationManager.IMPORTANCE_HIGH); // Here I tried put different channel name.
notificationChannel.setShowBadge(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
notificationChannel.canBubble();
}
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
notificationChannel.canShowBadge();
notificationChannel.enableVibration(true);
notificationChannel.setSound(soundUri, audioAttributes);
notificationManager.createNotificationChannel(notificationChannel);
notificationManager.notify(0, builder.build());
}
}
Finally, after researching a lot, I found a solution. All you need is this:-
While Creating Notification Channel, create different channels for Silent Notification, Custom Sound Notification, etc.
// The custom sound file name you want
val soundName = "beep"
val soundUri = Uri.parse("${ContentResolver.SCHEME_ANDROID_RESOURCE}://${packageName}/raw/${soundName}")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val importance = NotificationManager.IMPORTANCE_HIGH
val audioAttributes = AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build()
// Here The CHANNEL_ID is the main thing for creating a channel. Use this same CHANNEL_ID in Notification Builder Also.
val channel = NotificationChannel(CHANNEL_ID, getString(R.string.app_name), importance).apply {
description = getString(R.string.app_name)
setSound(null, audioAttributes) // Give Null if you want silent notification
// setSound(soundUri, audioAttributes)
}
notificationManager.createNotificationChannel(channel)
}
Notification Builder:-
// Here The CHANNEL_ID needs to be same like the above created channel id. Because it defines how notification sound come.
val builder = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(smallIcon)
with(notificationManager) {
notify(notificationId, builder.build())
}

How to send notification using oneSignal plugin in wordpress?

I'm new on SO, My problem is sending notification with image. I setup OneSignal plugin in wordpress website and created a sample android application. I am receiving notification but without large image.
In Android I'm getting this json in notification class.
{custom={"u":"https:my post url","i":"fe37dc8e-8e6c-4f00-9d69-a"}, alert=Kapil Sharma Show वापस आ रहा है नए मेहमान के साथ, जानिए कैसे हुआ शूट, title=My Website}
This is my method to show notification.
private fun sendNotification(notification: RemoteMessage.Notification?, data: Map<String, String>) {
val icon = BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher)
val intent = Intent(this, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT)
val notificationBuilder = NotificationCompat.Builder(this, "my_channel")
.setContentTitle(notification!!.title)
.setContentText(notification.body)
.setAutoCancel(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentIntent(pendingIntent)
.setContentInfo(notification.title)
.setLargeIcon(icon)
.setColor(Color.RED)
.setLights(Color.RED, 1000, 300)
.setDefaults(Notification.DEFAULT_VIBRATE)
.setSmallIcon(R.mipmap.ic_launcher)
try {
val picture_url = data["picture_url"]
if (picture_url != null && "" != picture_url) {
val url = URL(picture_url)
val bigPicture = BitmapFactory.decodeStream(url.openConnection().getInputStream())
notificationBuilder.setStyle(
NotificationCompat.BigPictureStyle().bigPicture(bigPicture).setSummaryText(notification.body)
)
}
} catch (e: IOException) {
e.printStackTrace()
}
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
// Notification Channel is required for Android O and above
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
"my_channel", "my_channel_name", NotificationManager.IMPORTANCE_DEFAULT
)
channel.description = "channel description"
channel.setShowBadge(true)
channel.canShowBadge()
channel.enableLights(true)
channel.lightColor = Color.RED
channel.enableVibration(true)
channel.vibrationPattern = longArrayOf(100, 200, 300, 400, 500)
notificationManager.createNotificationChannel(channel)
}
notificationManager.notify(0, notificationBuilder.build())
}
I just want to send notification with image when new post added in my wordpress site.

do not swipe out the notifcation message from notification bar on firebase on background using xamarin forms

I am using xamarin forms for app development. I am using firebase push notification for my app and using the following code for receiving notification. When my app is on foreground, the notification should not be swiped out, but when app is background we can swipe the notification. Please see the below code what i am using:
public override void OnMessageReceived(RemoteMessage message)
{
try
{
Android.Util.Log.Debug(TAG, "From: " + message.From);
Android.Util.Log.Debug(TAG, "Notification Message Body: " + message.GetNotification().Body);
SendNotifications(message);
}
catch (System.Exception ex)
{
Logs.LogCreate("OnMessageReceived Exception" + ex.Message);
Crashes.TrackError(ex);
}
}
public void SendNotifications(RemoteMessage message)
{
try
{
NotificationManager manager = (NotificationManager)GetSystemService(NotificationService);
var seed = Convert.ToInt32(Regex.Match(Guid.NewGuid().ToString(), #"\d+").Value);
int id = new Random(seed).Next(000000000, 999999999);
var push = new Intent();
var fullScreenPendingIntent = PendingIntent.GetActivity(this, 0,
push, PendingIntentFlags.CancelCurrent);
NotificationCompat.Builder notification;
if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
{
var chan1 = new NotificationChannel(PRIMARY_CHANNEL,
new Java.Lang.String("Primary"), NotificationImportance.High);
chan1.LightColor = Color.Green;
manager.CreateNotificationChannel(chan1);
notification = new NotificationCompat.Builder(this, PRIMARY_CHANNEL).SetOngoing(true);
}
else
{
notification = new NotificationCompat.Builder(this);
}
notification.SetContentIntent(fullScreenPendingIntent)
.SetContentTitle(message.GetNotification().Title)
.SetContentText(message.GetNotification().Body)
.SetLargeIcon(BitmapFactory.DecodeResource(Resources, Resource.Drawable.icon))
.SetSmallIcon(Resource.Drawable.icon_transparent)
.SetStyle((new NotificationCompat.BigTextStyle()))
.SetPriority(NotificationCompat.PriorityHigh)
.SetColor(0x9c6114)
.SetAutoCancel(true)
.SetOngoing(true);
manager.Notify(id, notification.Build());
}
catch (System.Exception ex)
{
}
}
Please give me suggestions for this.

Notification is not showing in Android 9

I am using this code to show notification in my android Application. This is working fine in all android version but no notification is showing in Android 9.
I tried to implement this with different method but nothing worked.
public void showNotification(String heading, String description, String imageUrl, Intent intent){
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
createChannel();
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,"channelID")
.setSmallIcon(R.drawable.logo)
.setContentTitle(heading)
.setContentText(description)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int notificationId = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);
notificationManager.notify(notificationId, notificationBuilder.build());
}
public void createChannel(){
if (Build.VERSION.SDK_INT < 26) {
return;
}
NotificationManager notificationManager =
(NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel channel = new NotificationChannel("channelID","name", NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("Description");
notificationManager.createNotificationChannel(channel);
}
Thanks..
Hi this is very Late Answer but I still want to mark the mistake in the code as well as the working code snippet so that It can help others.
you are having two instance of notificationManager on in the showNotification(..) function and another in the createChannel() function. You must create channel in the same instance of the notificationManager so your working code will be like:
public void showNotification(String heading, String description, String imageUrl, Intent intent){
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,"channelID")
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle(heading)
.setContentText(description)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int notificationId = 1;
createChannel(notificationManager);
notificationManager.notify(notificationId, notificationBuilder.build());
}
public void createChannel(NotificationManager notificationManager){
if (Build.VERSION.SDK_INT < 26) {
return;
}
NotificationChannel channel = new NotificationChannel("channelID","name", NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("Description");
notificationManager.createNotificationChannel(channel);
}
Call Like:
showNotification("Heading","Description","",new Intent(this,MainActivity.class));
The Results:

Resources