Firebase Push notification not receiving on Android 12 - android

My Xamarin.Android app's push notification only works on Android 11 (Pixel 3 XL). Currently my app targets Android 11, however it also runs on Android 12 (Pixel 6 Pro). The only thing that is not working is Firebase push notifications. Below is the code that I am using. For the past week I have been researching the issue and saw posts about a specific issue with Android 12 (Pixel 6) not recieving push notifications. I performed changes to the phone configurations that others suggested and another app notification began to work, yet mine still has not. Any ideas would help.Thanks.
if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
{
// Notification channels are new in API 26 (and not a part of the
// support library). There is no need to create a notification
// channel on older versions of Android.
var name = "NameOfChannel";
var description = "Notification Channel";
var channel = new NotificationChannel(CHANNEL_ID, name, NotificationImportance.Max)
{
Description = description
};
var notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.CreateNotificationChannel(channel);
}

What I was missed is
PendingIntent.FLAG_IMMUTABLE
If Notification has pendingIntent then set mutable/immutable Flag to it

Found the solution. Which was to add android:exported="false" on the Firebase service tag within the AndroidManifest.

PendingIntent pendingIntent;
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.S)
{
pendingIntent=PendingIntent.getActivity(context,notificationId,notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT|PendingIntent.FLAG_MUTABLE);
}
else
{
pendingIntent=PendingIntent.getActivity(context,notificationId,notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);
}
builder.setContentIntent(pendingIntent)

Im also facing the similar issue (Android/Kotlin), though i have modified Pending Intent changes and set "exported=false" still , app is not receiving the push notification.
below is firebase version
implementation platform('com.google.firebase:firebase-bom:31.0.3')
implementation 'androidx.work:work-runtime-ktx'
implementation 'com.google.firebase:firebase-messaging'
implementation 'com.google.firebase:firebase-iid'

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

Local notifications implementation

I'm trying to implement Local notifications(with click events and HeadUP Notifications) for my android application using Xamarin.Forms. I've followed Microsoft documentation for Local Notifications but I don't know how to implement this.Can anyone please share any working sample for this.
Thank You.
From Android official document ,there are two ways to set importance level.
First Solution: (Not Work)
If a notification's priority is flagged as High, Max, or full-screen, it gets a heads-up notification.
Examples of conditions that may trigger heads-up notifications include:
The notification has high priority and uses ringtones or vibrations.Using physical device to have a try as follow:
builder.SetVibrate(new long[0]);
builder.SetPriority((int)NotificationPriority.High);
Here is a similar discussion about Heads-up notification.
Unfortunately, the above solution does not work.
Second Solution:(Work)
The correct way in Xamarin Android can set property of Channel .If channel created by NotificationImportance.High,then can show heads-up.You can refer to this official sample.And Modify your CreateNotificationChannel method as follow:
void CreateNotificationChannel()
{
if (Build.VERSION.SdkInt < BuildVersionCodes.O)
{
// Notification channels are new in API 26 (and not a part of the
// support library). There is no need to create a notification
// channel on older versions of Android.
return;
}
var name = Resources.GetString(Resource.String.channel_name);
var description = GetString(Resource.String.channel_description);
//Replace follow NotificationImportance.Default to NotificationImportance.High
var channel = new NotificationChannel(CHANNEL_ID, name, NotificationImportance.High)
{
Description = description
};
var notificationManager = (NotificationManager) GetSystemService(NotificationService);
notificationManager.CreateNotificationChannel(channel);
}

Notification.Builder(context) deprecated Android O [duplicate]

This question already has answers here:
NotificationCompat.Builder deprecated in Android O
(10 answers)
Closed 5 years ago.
Notification.Builder(context) has been deprecated recently with the venue of Notification Channels in Android O.
PROBLEM:
After using Notification.Builder(context, StringID) instead of Notification.Builder(context)I did receive a notification to my Android O device.
However, after trying that on an Android 23 (M), I did not receive a notification. I debugged my code and it just stopped executing once the debugger hit the line post Notification.Builder(context, StringID) on Android 23 (M).
FIX:
To Fix this issue, I used if/else condition to segregate between Android O devices and the rest of other devices.
I have the following code snippet:
Notification.Builder notificationBuilder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationBuilder = new Notification.Builder(mContext,
mContext.getResources().getString(R.string.notification_id_channel));
} else {
notificationBuilder = new Notification.Builder(mContext);
}
Lint in Android Studio is displaying the following deprecation line:
QUESTION:
Is there a way to get rid off that deprecation warning line?
Your solution is to use NotificationCompat.Builder(Context context, String channelId). If you use this you don't have to check the API level, the Builder ignores the channel ID on pre-Oreo devices.
I have tested it on API 15, 22, 23, and 26 and it works perfectly.
You have to define a unique channelId (for example "MyChannelId_01") and call NotificationCompat.Builder (ctx, "MyChannelId_01"). The constructed Notification will be posted on this NotificationChannel "MyChannelId_01".
This alow you to define importance of the notification (this controls how interruptive notifications posted to this channel are. Value is IMPORTANCE_UNSPECIFIED, IMPORTANCE_NONE, IMPORTANCE_MIN, IMPORTANCE_LOW, IMPORTANCE_DEFAULT or IMPORTANCE_HIGH).
You can find an example here : Creating a notification channel
I had the same issue and since I am targeting android 22 and 24 I just did this:
NotificationCompat.Builder notification = new NotificationCompat.Builder(MainActivity.this, "")
I am sure someone will say this is a hack but it gets rid of the warning and I have no issues.
Seems passing an empty string works for < android 26.
Maybe someone else can state if this causes issues for 26.
Thanks

Android notification not showing up on API level 16

I'm trying to show a notification to the user in my Android application. I'm running two emulators at the moment. One is running at API level 16, and the other one is running at API level 25. When I send a notification to the application, the notification will only show up on the emulator which is running API level 25. I want to be able to show the notification on the emulator which is running API level 16 as well.
This is my code to show the notification to the user:
private void basicNotification(String title, String body, String data, Context context) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_monetization_on)
.setContentTitle(title)
.setContentText(body);
NotificationManager mNotifyMgr =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mNotifyMgr.notify(0, mBuilder.build());
}
Explanation parameters:
title = The title of the notification.
body = The body of the notification.
data = The data of the notification (not being used yet).
context = This is the context which I'm using to show the notification. This context is received from a class which extends FirebaseMessagingService.
When I execute the code above, I won't receive any errors. The only thing which will come up is in the logcat. The following line will appear:
05-11 07:47:42.169 1606-1758/system_process D/ConnectivityService: handleInetConditionHoldEnd: net=0, condition=100, published condition=100
I am not sure what I'm doing wrong right now. I used the official documentation from Android to make this method. If you need more information to solve the problem just let me know :)
So, after trying a few things, I found out I made a terrible mistake. The notification was showing up, but only in the drop down menu. For anyone who struggles with this, try to check your drop down menu if your notification is in there.
Related answer: https://stackoverflow.com/a/43809420/4653908

Android notification is not showing

I need a program that will add a notification on Android. And when someone clicks on the notification, it should lead them to my second activity.
I have established code. The notification should be working, but for some reason it is not working. The Notification isn't showing at all. I don't know what am I missing.
Code of those files:
Notification n = new Notification.Builder(this)
.setContentTitle("New mail from " + "test#gmail.com")
.setContentText("Subject")
.setContentIntent(pIntent).setAutoCancel(true)
.setStyle(new Notification.BigTextStyle().bigText(longText))
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Hide the notification after it's selected
notificationManager.notify(0, n);
The code won't work without an icon. So, add the setSmallIcon call to the builder chain like this for it to work:
.setSmallIcon(R.drawable.icon)
Android Oreo (8.0) and above
Android 8 introduced a new requirement of setting the channelId property by using a NotificationChannel.
NotificationManager mNotificationManager;
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(mContext.getApplicationContext(), "notify_001");
Intent ii = new Intent(mContext.getApplicationContext(), RootActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, ii, 0);
NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
bigText.bigText(verseurl);
bigText.setBigContentTitle("Today's Bible Verse");
bigText.setSummaryText("Text in detail");
mBuilder.setContentIntent(pendingIntent);
mBuilder.setSmallIcon(R.mipmap.ic_launcher_round);
mBuilder.setContentTitle("Your Title");
mBuilder.setContentText("Your text");
mBuilder.setPriority(Notification.PRIORITY_MAX);
mBuilder.setStyle(bigText);
mNotificationManager =
(NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
// === Removed some obsoletes
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);
mNotificationManager.createNotificationChannel(channel);
mBuilder.setChannelId(channelId);
}
mNotificationManager.notify(0, mBuilder.build());
Actually the answer by Ć’ernando Valle doesn't seem to be correct. Then again, your question is overly vague because you fail to mention what is wrong or isn't working.
Looking at your code I am assuming the Notification simply isn't showing.
Your notification is not showing, because you didn't provide an icon. Even though the SDK documentation doesn't mention it being required, it is in fact very much so and your Notification will not show without one.
addAction is only available since 4.1. Prior to that you would use the PendingIntent to launch an Activity. You seem to specify a PendingIntent, so your problem lies elsewhere. Logically, one must conclude it's the missing icon.
You were missing the small icon.
I did the same mistake and the above step resolved it.
As per the official documentation:
A Notification object must contain the following:
A small icon, set by setSmallIcon()
A title, set by setContentTitle()
Detail text, set by setContentText()
On Android 8.0 (API level 26) and higher, a valid notification channel ID, set by setChannelId() or provided in the NotificationCompat.Builder constructor when creating a channel.
See http://developer.android.com/guide/topics/ui/notifiers/notifications.html
This tripped me up today, but I realized it was because on Android 9.0 (Pie), Do Not Disturb by default also hides all notifications, rather than just silencing them like in Android 8.1 (Oreo) and before. This doesn't apply to notifications.
I like having DND on for my development device, so going into the DND settings and changing the setting to simply silence the notifications (but not hide them) fixed it for me.
Creation of notification channels are compulsory for Android versions after Android 8.1 (Oreo) for making notifications visible. If notifications are not visible in your app for Oreo+ Androids, you need to call the following function when your app starts -
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) {
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name,
importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviours after this
NotificationManager notificationManager =
getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
You also need to change the build.gradle file, and add the used Android SDK version into it:
implementation 'com.android.support:appcompat-v7:28.0.0'
This worked like a charm in my case.
I think that you forget the
addAction(int icon, CharSequence title, PendingIntent intent)
Look here: Add Action
I had the same issue with my Android app. I was trying out notifications and found that notifications were showing on my Android emulator which ran a Android 7.0 (Nougat) system, whereas it wasn't running on my phone which had Android 8.1 (Oreo).
After reading the documentation, I found that Android had a feature called notification channel, without which notifications won't show up on Oreo devices. Below is the link to official Android documentation on notification channels.
Notifications Overview, Notification anatomy
Create and Manage Notification Channels
For me it was an issue with deviceToken. Please check if the receiver and sender device token is properly updated in your database or wherever you are accessing it to send notifications.
For instance, use the following to update the device token on app launch. Therefore it will be always updated properly.
// Device token for push notifications
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(
new OnSuccessListener<InstanceIdResult>() {
#Override
public void onSuccess(InstanceIdResult instanceIdResult) {
deviceToken = instanceIdResult.getToken();
// Insert device token into Firebase database
fbDbRefRoot.child("user_detail_profile").child(currentUserId).child("device_token")).setValue(deviceToken)
.addOnSuccessListener(
new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
});
}
});
I encountered a similar problem to yours and while searching for a solution I found these answers but they weren't as direct as I hoped they would be but it gives an Idea; Your notifications may not be showing because for versions >=8 notifications are done relatively differently there is a NotificationChannel which aids in managing notifications this helped me. Happy coding.
void Note(){
//Creating a notification channel
NotificationChannel channel=new NotificationChannel("channel1",
"hello",
NotificationManager.IMPORTANCE_HIGH);
NotificationManager manager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.createNotificationChannel(channel);
//Creating the notification object
NotificationCompat.Builder notification=new NotificationCompat.Builder(this,"channel1");
//notification.setAutoCancel(true);
notification.setContentTitle("Hi this is a notification");
notification.setContentText("Hello you");
notification.setSmallIcon(R.drawable.ic_launcher_foreground);
//make the notification manager to issue a notification on the notification's channel
manager.notify(121,notification.build());
}
Make sure your notificationId is unique. I couldn't figure out why my test pushes weren't showing up, but it's because the notification ids were generated based on the push content, and since I was pushing the same notification over and over again, the notification id remained the same.
Notifications may not be shown if you show the notifications rapidly one after the other or cancel an existing one, then right away show it again (e.g. to trigger a heads-up-notification to notify the user about a change in an ongoing notification). In these cases the system may decide to just block the notification when it feels they might become too overwhelming/spammy for the user.
Please note, that at least on stock Android (tested with 10) from the outside this behavior looks a bit random: it just sometimes happens and sometimes it doesn't. My guess is, there is a very short time threshold during which you are not allowed to send too many notifications. Calling NotificationManager.cancel() and then NotificationManager.notify() might then sometimes cause this behavior.
If you have the option, when updating a notification don't cancel it before, but just call NotificationManager.notify() with the updated notification. This doesn't seem to trigger the aforementioned blocking by the system.
If you are on version >= Android 8.1 (Oreo) while using a Notification channel, set its importance to high:
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
val pendingIntent = PendingIntent.getActivity(applicationContext, 0, Intent(), 0)
var notification = NotificationCompat.Builder(applicationContext, CHANNEL_ID)
.setContentTitle("Title")
.setContentText("Text")
.setSmallIcon(R.drawable.icon)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent)
.build()
val mNotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
mNotificationManager.notify(sameId, notification)

Categories

Resources