I am using azure hub notification.
I am developing my app in Xamarin.Forms. For android I can get notification when I test it hits to debug and i can show a DisplayAlert for that.
But I cannot show it as notification. I searched and after android oreo I should create a notification channel.
But I don't know how to do it. They are saying that you should create a notification id in your strings.xml but I don't have strings.xml file. I dont know how to do it, can anyone help?
internal static readonly string CHANNEL_ID = "cross_channel";
void CreateNotification(string title, string desc)
{
var notificationManager = GetSystemService(Context.NotificationService)
as NotificationManager;
var uiIntent = new Intent(this, typeof(MainActivity));
var pendingIntent = PendingIntent.GetActivity(this, RandomGenerator(), uiIntent, PendingIntentFlags.OneShot);
var notification = new Notification(Android.Resource.Drawable.ButtonMinus, title)
{
Flags = NotificationFlags.AutoCancel
};
notification.SetLatestEventInfo(this, title, desc,
PendingIntent.GetActivity(this, 0, uiIntent, 0));
if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
{
var channel = new NotificationChannel(CHANNEL_ID,
"Cross Notifications",
NotificationImportance.High);
notificationManager.CreateNotificationChannel(channel);
string channelId = "Cross Channel";
var notBuilder = new Notification.Builder(Application.Context, CHANNEL_ID).SetContentTitle(title).SetContentText(desc).SetSmallIcon(Android.Resource.Drawable.StarBigOn).SetAutoCancel(true);
notificationManager.Notify(1, notBuilder.Build());
channel.Description = (desc);
notBuilder.SetChannelId(channelId);
}
notificationManager.Notify(RandomGenerator(), notBuilder.Build());
}
I had a bit of trouble getting notifications properly showing on with Xamarin.Forms also. I'm assuming you have overridden the "OnMessageReceived" event and you're calling "CreateNotification" directly? In the end, this was the code that worked for me:
private void ShowNotification(RemoteMessage msg, IDictionary<string, string> data)
{
var intent = new Intent();
intent.AddFlags(ActivityFlags.ClearTop);
foreach (var key in data.Keys)
intent.PutExtra(key, data[key]);
var pendingIntent = PendingIntent.GetActivity(Android.App.Application.Context, 100, intent, PendingIntentFlags.OneShot);
var notificationBuilder = new NotificationCompat.Builder(Android.App.Application.Context) // Note: Everything I read online said to provide the ChannelID string here, but doing so caused it to not display notifications.
.SetSmallIcon(Resource.Drawable.abc_btn_radio_to_on_mtrl_000) // You can set this to your apps icon
.SetContentTitle(msg.GetNotification().Title)
.SetContentText(msg.GetNotification().Body)
.SetPriority((int)Android.App.NotificationImportance.Max)
.SetDefaults(NotificationCompat.DefaultAll)
.SetContentIntent(pendingIntent) // Even though intent here is empty, you *may* need to include it for the notification to show, I never tried without one.
.SetVisibility((int)NotificationVisibility.Public);
var notificationManager = NotificationManagerCompat.From(Android.App.Application.Context);
notificationManager.Notify(100, notificationBuilder.Build());
}
In the MainActivity.cs You can call this method in the onCreate method :
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 channel = new NotificationChannel(CHANNEL_ID, "FCM Notifications", NotificationImportance.Default)
{
Description = "Firebase Cloud Messages appear in this channel"
};
var notificationManager = (NotificationManager) GetSystemService(NotificationService);
notificationManager.CreateNotificationChannel(channel);
}
Where
internal static readonly string CHANNEL_ID = "my_notification_channel";
internal static readonly int NOTIFICATION_ID = 100;
are the definition for channel id and notification id respectively.
In the MainActivity's OnCreate after loading XF call this :
LoadApplication(new App());
CreateNotificationChannel();
Good luck
Revert in case of queries
Related
I have implemented the push notification using FCM in my xamarin forms android project. When I tap on the notification I will show the corresponding content page also.
My code for showing the notification on UI using notificationBuilder
public void SendNotificatios(string body, string Header)
{
var intent = new Intent(this, typeof(MainActivity));
intent.AddFlags(ActivityFlags.ClearTop);
var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
if (Build.VERSION.SdkInt < BuildVersionCodes.O)
{
var notificationBuilder = new NotificationCompat.Builder(this)
.SetContentTitle(Header)
.SetSmallIcon(Resource.Drawable.icon)
.SetContentText(body)
.SetAutoCancel(true)
.SetContentIntent(pendingIntent);
var notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;
notificationManager.Notify(0, notificationBuilder.Build());
//notificationManager.Notify(new Random().Next(), notificationBuilder.Build());
}
else
{
var notificationBuilder = new NotificationCompat.Builder(this, Utils.CHANNEL_ID)
.SetContentTitle(Header)
.SetSmallIcon(Resource.Drawable.icon)
.SetContentText(body)
.SetAutoCancel(true)
.SetContentIntent(pendingIntent);
var notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;
NotificationChannel channel = new NotificationChannel(Utils.CHANNEL_ID, "FCM Notifications", NotificationImportance.Default);
notificationManager.CreateNotificationChannel(channel);
notificationManager.Notify(0, notificationBuilder.Build());
//notificationManager.Notify(new Random().Next(), notificationBuilder.Build());
}
}
I have implemented the notification tapping like below:
MainActivity:
//Background or killed mode
if (Intent.Extras != null)
{
foreach (var key in Intent.Extras.KeySet())
{
var value = Intent.Extras.GetString(key);
Log.Debug(TAG, "Key: {0} Value: {1}", key, value);
if (key == "webContentList") // Make it Dynamic instead of hardcoding here
{
if (value?.Length > 0)
{
isNotification = true;
LoadApplication(new App(value));
}
}
}
}
//Foreground mode
if (FirebaseNotificationService.webContentList.ToString() != "")
{
isNotification = true;
LoadApplication(new App(FirebaseNotificationService.webContentList.ToString()));
FirebaseNotificationService.webContentList = "";
}
//Normal loading
if (!isNotification)
{
LoadApplication(new App(string.Empty));
}
On App.xaml.cs:
public App(string domain, string isNotification)
{
//Notification tapping section
if ((!String.IsNullOrEmpty(isNotification) && isNotification?.Length > 0) || _webContentList != null)
{
_webContentList = JsonConvert.DeserializeObject<List<webContentList>>(isNotification);
MainPage = new DashBoardPage(_webContentList[0],null, isGroup);//loading the corresponsing page
}
else if (domain == "")//normal loading
{
MainPage = new SmartWCM.MainPage(domain, false);
}
}
Currently, only one notification will show on the phone. The new notifications will clear the old one and the last notification will show on the UI. This is happening because I have set 0 as the value inside notificationManager.Notify.
notificationManager.Notify(0, notificationBuilder.Build());
If I change it like a random number like below all notification will show on UI.
notificationManager.Notify(new Random().Next(), notificationBuilder.Build());
My problem at this stage(when multiple notifications are visible on UI) how I can implement the notifications tapping? If I click any notification only the last notifications corresponding page will open. Any solution for this.
For an assignment, I have to write an application which can display all contacts and their birthday date (& create / modify them). So far so good. Then, I have to fire a notification with all people who are born today.
The notification is launched without problem but I don't get the app icon badge.
After searching, I found out I have to use the channels -> done.
I've verified in the settings if the notification dot is enabled:
I've verified the android documentation saying "it's automatic you shoundn't have anything to do"
My simulator is using Android 9.0 which is greater than android oreo.
So what's wrong ?
public class BirthdayListener implements View.OnClickListener {
private static final String CHANNEL_ID = "ch.hefr.tic.birthday_channel";
private static final int SUMMARY_ID = -1;
private static final String GROUP_KEY = "ch.hefr.tic.group_channel";
private Context context;
private NotificationManager notificationManager;
public BirthdayListener(Context context) {
this.context = context;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = context.getResources().getString(R.string.channel_name);
String description = context.getResources().getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
channel.setShowBadge(true);
notificationManager = context.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
#Override
public void onClick(View v) {
List<Contact> hasBirthday = searchBirthdays();
NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context);
NotificationCompat.InboxStyle summaryStyle = new NotificationCompat.InboxStyle();
summaryStyle.setBigContentTitle(hasBirthday.size() + " new messages");
for(int i = 0; i < hasBirthday.size(); ++i) {
Contact contact = hasBirthday.get(i);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_notification)
.setContentTitle("Birthday")
.setContentText(contact.getName() + " has his birthday today !")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setGroup(GROUP_KEY)
.setNumber(5);
String phoneNumber = contact.getPhoneNumber();
if(phoneNumber != null && !phoneNumber.equals("")) {
Intent smsIntent = new Intent(Intent.ACTION_VIEW);
smsIntent.setData(Uri.parse("sms:" + phoneNumber));
PendingIntent pending = PendingIntent.getActivity(context, 0, smsIntent, 0);
builder.addAction(R.drawable.ic_arrow_back, "SMS", pending);
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O)
notificationManagerCompat.notify(i, builder.build());
else
notificationManager.notify(i, builder.build());
}
NotificationCompat.Builder summaryBuilder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_notification)
.setContentTitle("Today Birthdays")
.setContentText(hasBirthday.size() + " new messages")
.setStyle(summaryStyle)
.setGroup(GROUP_KEY)
.setGroupSummary(true)
.setNumber(5);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O)
notificationManagerCompat.notify(SUMMARY_ID, summaryBuilder.build());
else
notificationManager.notify(SUMMARY_ID, summaryBuilder.build());
}
}
Edit : tried to use the setColor on NotificationCompat.Builder builder but it changes the color of the icon. Still don't have any badge.
Thanks to Bob and his link : https://support.google.com/pixelphone/thread/1575301?hl=en,
I found out I had to go to settings < apps and notifications < special app access < notifications < notification access < turn on for "pixel launcher". Then the notification dots would appear as expected !
Well time to write my report I guess.
I am making MQTT client app using paho MQTT client dependency.
Implementing code in a Background Service. and everything works well except the Notification isn't working!
Service code snippet is here:
My Codes occurs inside the TimeDisplayTimerTask inner-class.
This code located at the callback function :
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
mIntent = new Intent(getApplicationContext(), MainActivity.class);
mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, mIntent, 0);
createNotificationChannel();
Toast.makeText(getApplicationContext(),"A message received : "+ new String(message.getPayload()),Toast.LENGTH_SHORT).show();
vibrator.vibrate(500);
myRingtone.play();
mBuilder .setContentTitle("Message received at : " + mTopic)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setContentText("Message : "+ new String(message.getPayload()));
mNotificationManager.notify(0, mBuilder.build());
}
And this code creates a notification channel (as Google developers guide mentioned to write):
Posted with help of this answer.
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String chanel_id = "3000";
CharSequence name = "Mqtt message";
String description = "Message arrived";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel mChannel = new NotificationChannel(chanel_id, name, importance);
mChannel.setDescription(description);
mChannel.enableLights(true);
mChannel.setLightColor(Color.BLUE);
mNotificationManager = getSystemService(NotificationManager.class);
if (mNotificationManager != null) {
mNotificationManager.createNotificationChannel(mChannel);
}
mBuilder = new NotificationCompat.Builder(getApplicationContext(), chanel_id);
}
else
{
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(getApplicationContext());
}
}
When it receives a message, A toast message appears holding the message.
But it doesn't push notification.
Checked Apps and Notifications, All notifications are allowed.
SOLVED :
the setter method .setSmallIcon must be called to successfully build a notification.
Which was not important to me.
I am facing some Notification related issue in Oreo Version only. I follow this link and successfully got custom sound after uninstall/install the app as he has suggested.
Now problem is that I want to use two custom sound in my app, For that, I have code like:
private void sendNotification(NotificationBean notificationBean) {
String textTitle = notificationBean.getTitle();
String alert = notificationBean.getMessage().getAlert();
int orderId = notificationBean.getMessage().getOrderId();
String notificationType = notificationBean.getMessage().getNotificationType();
String sound = notificationBean.getMessage().getSound();
Intent intent = new Intent(this, NavigationDrawerActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri soundUri;
if (notificationType.equals("Pending"))
soundUri = Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.sound);
else
soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, getString(R.string.app_name))
.setSmallIcon(R.drawable.ic_stat_name)
.setContentTitle(textTitle)
.setContentText(alert)
.setSound(soundUri)
.setContentIntent(pendingIntent)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
// 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.app_name);
String description = getString(R.string.app_name);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(getString(R.string.app_name), name, importance);
channel.setDescription(description);
AudioAttributes attributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
channel.enableLights(true);
channel.enableVibration(true);
channel.setSound(soundUri, attributes);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
// notificationId is a unique int for each notification that you must define
notificationManager.notify(101, mBuilder.build());
}
If I get notificationType = "Pending" then I want to use custom sound, otherwise DEFAULT sound but Here It is playing that sound which is played first-time (When I receive notification first time.).
I am getting this problem in OREO only. In all other devices its working fine.
Any help? Your help would be appreciated.
Problem:
It seems Notification Channel issue.
Solution:
Either you should create separate channel, or you should delete your own channel.
Strategy:
1) Create separate channel:
You may select this strategy if you want to persist multiple channels along with various configuration for your app.
To create separate channel, just provide unique channel ID while creating it.
i.e.:
NotificationChannel channel = new NotificationChannel(uniqueChannelId, name, importance);
2) Delete your existing channel and re-create it:
You may select this strategy if you want to persist only one channel along with updated configuration for your app.
To delete your own channel and re-create it, following may work fine:
NotificationManager mNotificationManager = getSystemService(NotificationManager.class);
NotificationChannel existingChannel = notificationManager.getNotificationChannel(channelId);
//it will delete existing channel if it exists
if (existingChannel != null) {
mNotificationManager.deleteNotificationChannel(notificationChannel);
}
//then your code to create channel
NotificationChannel channel = new NotificationChannel(channelId, name, importance);
I got hint to solve my problem from #Mehul Joisar's answer.
As he wrote:
Either you should create separate channel, or you should delete your
own channel.
I have created two separate channels for different sounds.
As I think, we cant change Notification Channel settings after once we
have created channel. We must have to remove and create new or else We
have to create separate channels for different settings.
Here I am sharing full code to help others.
private void sendNotification(NotificationBean notificationBean) {
String textTitle = notificationBean.getTitle();
String alert = notificationBean.getMessage().getAlert();
int orderId = notificationBean.getMessage().getOrderId();
String notificationType = notificationBean.getMessage().getNotificationType();
Intent intent = new Intent(this, NavigationDrawerActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Uri soundUri;
String channelName;
if (notificationType.equals("Pending")) {
channelName = getString(R.string.str_chef);
soundUri = Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.sound);
}
else {
channelName = getString(R.string.str_customer);
soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, channelName)
.setSmallIcon(R.drawable.ic_stat_name)
.setContentTitle(textTitle)
.setContentText(alert)
.setSound(soundUri)
.setContentIntent(pendingIntent)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
// 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.app_name);
String description = getString(R.string.app_name);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(channelName, name, importance);
channel.setDescription(description);
AudioAttributes attributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
channel.enableLights(true);
channel.enableVibration(true);
channel.setSound(soundUri, attributes);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
// notificationId is a unique int for each notification that you must define
notificationManager.notify(101, mBuilder.build());
}
NOTE: Must uninstall your app first and then test with this code.
Thank you.
I am trying to make push notification using Firebase to my app. I tried it and it works perfectly in the background in Oreo, but when I try to open the app and send a notification from another account, the notification does not appear.
How do I solve this and where is the problem in my code?
This is part of the code of my service:
public class FirebaseMessagingService extends
com.google.firebase.messaging.FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String messageTitle = remoteMessage.getNotification().getTitle();
String messageBody = remoteMessage.getNotification().getBody();
NotificationCompat.Builder builder = new NotificationCompat.Builder(
this, getString(R.string.default_notification_channel_id))
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle(messageTitle)
.setContentText(messageBody);
Intent resultIntent = new Intent(this, MainAdsActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
int id = (int) System.currentTimeMillis();
builder.setContentIntent(pendingIntent);
startForeground(id,builder.build());
NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(id, builder.build());
}
}
Android manifest file:
<service
android:name=".FirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="#string/default_notification_channel_id"/>
Cloud functions
const functions = require('firebase-functions');
const admin=require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const api = admin.firestore()
api.settings({timestampsInSnapshots: true})
exports.fuync=functions
.firestore.document("Users/{userid}/notification/{notification_id}")
.onWrite((change,context)=>{
const userid=context.params.userid;
const notification_id=context.params.notification_id;
return admin.firestore().collection('Users')
.doc(userid).collection('notification')
.doc(notification_id).get().then(queryRes
ult=>{
const fromuserid=queryResult.data().from;
const frommessage=queryResult.data().message;
const
fromdata=admin.firestore()
.collection('Users').doc(fromuserid).get();
const todata=admin.firestore()
.collection('Users').doc(userid).get();
return Promise.all([fromdata,todata]).then(result=>{
const fromname=result[0].data().name;
const toname=result[1].data().name;
const tokenid=result[1].data().token_id;
//return console.log("from :" +fromname + "TO: " +toname);
const payload= {
notification: {
title : "notification from" +fromname,
body : frommessage,
icon : "default"
}
};
return admin.messaging().sendToDevice(tokenid,payload).then(result=>{
return console.log("NOTIFICATION SENT.");
});
});
});
});
build gradle
android {
compileSdkVersion 27
defaultConfig {
applicationId "com.example.amr.app"
minSdkVersion 18
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner
buildToolsVersion '27.0.3'
}
This is the solution I have done and works perfectly in foreground and background for Oreo version and higher versions.
Creating a notification channel is very crucial. The most important thing is the String id inside NotificationChannel channel = new NotificationChannel().
it must be the one provided by firebase which is : default_notification_channel_id
and the code will be like this:
private static final CharSequence NAME = "amro";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
//____ID _____
int id = (int) System.currentTimeMillis();
//_____NOTIFICATION ID'S FROM FCF_____
String messageTitle = remoteMessage.getNotification().getTitle();
String messageBody = remoteMessage.getNotification().getBody();
NotificationCompat.Builder builder =
new NotificationCompat
.Builder(this, getString(R.string.default_notification_channel_id))
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle(messageTitle)
.setContentText(messageBody);
//_____REDIRECTING PAGE WHEN NOTIFICATION CLICKS_____
Intent resultIntent = new Intent(this, ProfileActivity.class);
PendingIntent pendingIntent = PendingIntent
.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT
);
builder.setContentIntent(pendingIntent);
if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ) {
int importance = NotificationManager.IMPORTANCE_HIGH;
String channelID = BuildConfig.APPLICATION_ID;
NotificationChannel channel = new NotificationChannel
(getString(R.string.default_notification_channel_id), BuildConfig.APPLICATION_ID, importance);
channel.setDescription(channelID);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
//assert notificationManager != null;
notificationManager.createNotificationChannel(channel);
}
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
assert notificationManager != null;
notificationManager.notify(id, builder.build());
}
Since android oreo there is Channel
When you target Android 8.0 (API level 26), you must implement one or more notification channels. If your targetSdkVersion is set to 25 or lower, when your app runs on Android 8.0 (API level 26) or higher, it behaves the same as it would on devices running Android 7.1 (API level 25) or lower.
try to using support library 26 or later and check this Create and Manage Notification Channels
try to use this method to create NotificationCompat.Builder
public NotificationCompat.Builder initChannels() {
if (Build.VERSION.SDK_INT < 26) {
return new NotificationCompat.Builder(this);
}
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String id = BuildConfig.APPLICATION_ID;
NotificationChannel channel = new NotificationChannel(id, BuildConfig.APPLICATION_ID, NotificationManager.IMPORTANCE_HIGH);
channel.setDescription(BuildConfig.APPLICATION_ID);
notificationManager.createNotificationChannel(channel);
return new NotificationCompat.Builder(this, id);
}
the create new instance from this method
NotificationCompat.Builder builder = initChannels();
String messageTitle = remoteMessage.getNotification().getTitle();
String messageBody = remoteMessage.getNotification().getBody();
try
String messageTitle = remoteMessage.getData().getTitle();
String messageBody = remoteMessage.getData().getBody();
First add logs in onMessageArrived()
Log.d("Firebase PM service", "onMessageArrived called");
and check if you are getting this log in LogCat.
If you don't, then something is not working properly on Firebase end.
If you are receiving it, then it means you are doing something wrong after getting push msg(i.e. not displaying notification properly). Also check LogCat whether any exception is thrown or not.
Then post your replay.
Use the below code in FirebaseMessagingService.
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String messageTitle = remoteMessage.getNotification().getTitle();
String messageBody = remoteMessage.getNotification().getBody();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = “Your channel name, It will be visible in app setting”;
String description =“Description for your channel”;
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(SOME_CHANNEL_ID, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
NotificationCompat.Builder builder = new NotificationCompat
.Builder(this, getString(R.string.default_notification_channel_id))
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle(messageTitle)
.setContentText(messageBody);
Intent resultIntent = new Intent(this, MainAdsActivity.class);
PendingIntent pendingIntent = PendingIntent
.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT
);
int id = (int) System.currentTimeMillis();
builder.setContentIntent(pendingIntent);
startForeground(id,builder.build());
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(id, builder.build());
}
}