Firebase notifications don't ring on Redmi Note 8T - android

This is the use case:
When I receive a notification on the channel "channel1" I would like:
- if app is foregrounded: ActivityTest opens automatically
- if app is backgrounded: I receive a notification with the sound specified (I also specified the name of the sound on the backend)
Is my code correct? I have tested it on 3 devices and on two it works correctly while on the third (Redmi Note 8T) there is neither sound nor vibration, although I have granted notification and sound permissions from the smartphone settings. As you can see from the commented code, I tried different combinations, but nothing changed. What could be the problem?
String CHANNEL_ID = "channel1";
CharSequence name = "channel1";
String Description = "This is my channel";
int NOTIFICATION_ID = 234;
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
Uri defaultSoundUri = Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.soundname);
// Since android Oreo notification channel is needed.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
AudioAttributes.Builder audioAttributesBuilder = new AudioAttributes.Builder();
//.setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION_SIGNALLING)
//.setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
//.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
//.setContentType(AudioAttributes.CONTENT_TYPE_UNKNOWN)
//.setFlags(AudioAttributes.FLAG_AUDIBILITY_ENFORCED);
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, name, importance);
notificationChannel.setDescription(Description);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
notificationChannel.setSound(defaultSoundUri, audioAttributesBuilder.build());
notificationChannel.setShowBadge(true);
if (notificationManager != null) {
notificationManager.createNotificationChannel(notificationChannel);
}
}
Intent intent = new Intent(this, ActivityTest.class);
//intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra(Constant.id, id);
if(Applicazione.getInstance().isAppForegrounded()) {
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} else {
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setStyle(new NotificationCompat.BigTextStyle().bigText(message))
.setColor(getResources().getColor(R.color.acqua_marina))
.setSmallIcon(R.drawable.icon_notifica)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
//.setSound(defaultSoundUri)
//.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setSound(defaultSoundUri, AudioManager.STREAM_RING)
//.setSound(defaultSoundUri, AudioManager.RINGER_MODE_NORMAL)
.setPriority(NotificationCompat.PRIORITY_HIGH);
//.setCategory(NotificationCompat.CATEGORY_CALL);
//.setFullScreenIntent(pendingIntent, true);
if (notificationManager != null) {
notificationManager.notify(NOTIFICATION_ID, builder.build());
}
}

Related

samsung wear watch notification issue

Im trying to show notification on wear watch anything is goes correct but My Remote input choice are not visible on samsung watch it will show only title and Body my input choice are not visible on it.
It appears on my phone, but it doesn't appear on my watch connected to my phone. Is there something missing from the code that's required for Android Wear?
I'm using this code for display notification on watch
public void getNotifcation(){
RemoteInput ri = new RemoteInput.Builder(KEY_TEXT_REPLY) .setLabel(body) .setChoices(replyChoices) .build();
NotificationCompat.Action a =
new NotificationCompat.Action.Builder(R.drawable.ic_send_arraow_red,
null, getReplyPendingIntent())
.addRemoteInput(ri)
.build();
Uri defaultSoundUri = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_NOTIFICATION);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, getString(R.string.default_notification_channel_id))
.setSmallIcon(R.drawable.ic_noti_icon)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_notification))
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setVibrate(new long[]{200, 400, 600, 800})
.setOngoing(false)
.setGroup("GROUP")
.setGroupSummary(false)
.setContentIntent(notifyPendingIntent)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.addAction(a)
.extend(new NotificationCompat.WearableExtender().addAction(a));
NotificationCompat.WearableExtender extender =
new NotificationCompat.WearableExtender();
extender.addAction(new NotificationCompat.Action.Builder(R.drawable.ic_send_arraow_red, "send" ,
getReplyPendingIntent())
.addRemoteInput(ri).build());
notificationBuilder.extend(extender);
//Wear OS requires a hint to display the reply action inline.
NotificationCompat.Action.WearableExtender actionExtender =
new NotificationCompat.Action.WearableExtender()
.setHintLaunchesActivity(true)
.setHintDisplayActionInline(true);
notificationBuilder.addAction(noti.extend(actionExtender).build());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(channelId, "Notifications",
NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setDescription(messageBody);
notificationChannel.enableLights(true);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{200, 400, 600, 800});
notificationChannel.setLightColor(Color.RED);
if (defaultSoundUri != null) {
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build();
notificationChannel.setSound(defaultSoundUri, audioAttributes);
}
notificationManager.createNotificationChannel(notificationChannel);
}
notificationManager.notify(notificationId notificationBuilder.build());
}
and here is my pending intent to get choice on wear
public void getReplyPendingIntent(){
Intent intent;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // start a // (i) broadcast receiver which runs on the UI thread or // (ii) service for a background task to b executed,will be doing a broadcast receiver
intent = new Intent(context, FcmBroadcastReceiver.class);
intent.setAction(REPLY_ACTION);
intent.putExtra(KEY_NOTIFICATION_ID, notificationId);
intent.putExtra(KEY_TEXT_REPLY, KeyReply);
return PendingIntent.getBroadcast(getApplicationContext(), 100, intent,
PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
} else {
// start your activity
intent = Act_Home.getReplyMessageIntent(this, notificationId, 123);
return PendingIntent.getActivity(this, 100, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
}
}

Push Notifications don't vibrate when app is closed

On Android 10, when I receive push notification, the vibration only works if app is opened. If it's in background or closed, vibration doesn't work (but notification get's through and sound works). Is this a bug? Couldn't find it in Google's bug-tracker though.
I send the push notification from our server with data payload, which ensures onMessageReceived() gets called even if app is in background. And it does, I can debug it.
Here's how notification channel is created:
NotificationChannel mChannelUp = new NotificationChannel(CHANNEL_ID_ALERTS_UP, getApplicationContext().getString(R.string.alerts_up), NotificationManager.IMPORTANCE_HIGH);
mChannelUp.enableLights(true);
mChannelUp.enableVibration(true);
// mChannelUp.setVibrationPattern(new long[]{500, 250, 500, 250}); // doesn't help
mChannelUp.setLightColor(Color.BLUE);
AudioAttributes audioAttributesUp = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION_EVENT)
.build();
mChannelUp.setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/" + R.raw.notif_sound_up), audioAttributesUp);
notificationManager.createNotificationChannel(mChannelUp);
And the notification itself:
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this, CHANNEL_ID_ALERTS_UP)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_notif)
.setColor(ContextCompat.getColor(this, R.color.colorPrimary))
.setLargeIcon(logo)
.setVibrate(new long[]{250, 500, 250, 500})
.setLights(Color.parseColor("#039be5"), 500, 500)
.setContentTitle("some title")
.setContentText("some content")
.setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/" + R.raw.notif_sound_up));
mBuilder.setContentIntent(resultPendingIntent);
Notification notif = mBuilder.build();
NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(notificationId, notif);
You need to call the vibration service.
vibrator = (Vibrator)getSystemService(VIBRATOR_SERVICE);
vibrator.vibrate(2000);
if Your device set Automatically miscellaneous notification channel in notification channel
you can try Firebase default Chanel
public static String NOTIFICATION_CHANNEL_ID ="fcm_fallback_notification_channel";
Channel
NotificationManager notificationManager = mContext.GetSystemService(Context.NotificationService) as NotificationManager;
if (global::Android.OS.Build.VERSION.SdkInt >= global::Android.OS.BuildVersionCodes.O)
{
NotificationImportance importance = global::Android.App.NotificationImportance.High;
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, title, importance);
notificationChannel.EnableLights(true);
notificationChannel.EnableVibration(true);
notificationChannel.SetSound(sound, alarmAttributes);
notificationChannel.SetShowBadge(true);
notificationChannel.Importance = NotificationImportance.High;
notificationChannel.SetVibrationPattern(new long[] { 100, 200, 300, 400, 500, 400, 300, 200, 400 });
if (notificationManager != null)
{
mBuilder.SetChannelId(NOTIFICATION_CHANNEL_ID);
notificationManager.CreateNotificationChannel(notificationChannel);
}
}
notificationManager.Notify(0, mBuilder.Build());
my class :
class NotificationHelper : INotification
{
private Context mContext;
private NotificationManager mNotificationManager;
private NotificationCompat.Builder mBuilder;
public static String NOTIFICATION_CHANNEL_ID = "fcm_fallback_notification_channel";
public NotificationHelper()
{
mContext = global::Android.App.Application.Context;
}
public void CreateNotification(String title, String message)
{
try
{
var intent = new Intent(mContext, typeof(MainActivity));
intent.AddFlags(ActivityFlags.ClearTop);
intent.PutExtra(title, message);
var pendingIntent = PendingIntent.GetActivity(mContext, 0, intent, PendingIntentFlags.OneShot);
var sound = global::Android.Net.Uri.Parse(ContentResolver.SchemeAndroidResource + "://" + mContext.PackageName + "/"+Resource.Raw.notification);//add sound
// Creating an Audio Attribute
var alarmAttributes = new AudioAttributes.Builder()
.SetContentType(AudioContentType.Sonification)
.SetUsage(AudioUsageKind.Notification).Build();
mBuilder = new NotificationCompat.Builder(mContext);
mBuilder.SetSmallIcon(Resource.Drawable.INH_ICON1);
mBuilder.SetContentTitle(title)
.SetSound(sound)
.SetAutoCancel(true)
.SetContentTitle(title)
.SetContentText(message)
.SetChannelId(NOTIFICATION_CHANNEL_ID)
.SetPriority((int)NotificationPriority.High)
.SetLights(65536, 1000, 500)
//.SetColor(Resource.Color.)
.SetVibrate(new long[] { 100, 200, 300, 400, 500, 400, 300, 200, 400 })
.SetDefaults((int)NotificationDefaults.Sound | (int)NotificationDefaults.Vibrate)
.SetVisibility((int)NotificationVisibility.Public)
.SetSmallIcon(Resource.Drawable.INH_ICON1)
.SetContentIntent(pendingIntent);
NotificationManager notificationManager = mContext.GetSystemService(Context.NotificationService) as NotificationManager;
if (global::Android.OS.Build.VERSION.SdkInt >= global::Android.OS.BuildVersionCodes.O)
{
NotificationImportance importance = global::Android.App.NotificationImportance.High;
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, title, importance);
notificationChannel.EnableLights(true);
notificationChannel.EnableVibration(true);
notificationChannel.SetSound(sound, alarmAttributes);
notificationChannel.SetShowBadge(true);
notificationChannel.Importance = NotificationImportance.High;
notificationChannel.SetVibrationPattern(new long[] { 100, 200, 300, 400, 500, 400, 300, 200, 400 });
if (notificationManager != null)
{
mBuilder.SetChannelId(NOTIFICATION_CHANNEL_ID);
notificationManager.CreateNotificationChannel(notificationChannel);
}
}
notificationManager.Notify(0, mBuilder.Build());
}
catch (Exception ex)
{
//
}
}
}
By the reference of Firebase, when your app is in the background, the notification is delivered to the device’s system tray. A user tap on a notification opens the app launcher by default.
Messages with both notification and data payload, when received in the background. In this case, the notification is delivered to the device’s system tray, and the data payload is delivered in the extras of the intent of your launcher Activity. That time vibration could not happen.
You can try to wake up the application when u received a notification. That might help you.
Firebase Reference
Android Pie And Newer version have some limitations. Check this reference
Suggesting to question here: https://eu.community.samsung.com/t5/galaxy-s10e-s10-s10-s10-5g/s10-has-stopped-vibrating-when-reciving-notifications/m-p/1567092
Try heading to: Settings > Sound and vibration > Vibration intensity > Turn all options to max.
I've now noticed this in the Logcat:
Ignoring incoming vibration as process with uid = 10587 is background,
usage = USAGE_NOTIFICATION_EVENT
To make vibration work even when app in background, you need to use AudioAttributes.USAGE_NOTIFICATION (USAGE_NOTIFICATION_EVENT won't work!) AND also setVibrationPattern on channel:
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build();
NotificationChannel mChannelUp = new NotificationChannel(CHANNEL_ID_ALERTS_UP, getApplicationContext().getString(R.string.alerts_up), NotificationManager.IMPORTANCE_HIGH);
mChannelUp.enableLights(true);
mChannelUp.enableVibration(true);
mChannelUp.setVibrationPattern(new long[]{0, 300, 250, 300, 250, 300});
mChannelUp.setLightColor(Color.BLUE);
mChannelUp.setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/" + R.raw.notif_sound_up), audioAttributes);
notificationManager.createNotificationChannel(mChannelUp);
Now vibration works when app in background too.
Thanks to ijigarsolanki's answer which helped me realize this.

Failed to post notification on channel if application is active

I am trying to integrate firebase notifications and I get a "failed to post notification on channel" error when trying to process received notifications.
This issue only happens when application is in the foregroud.
If it is in the background, notifications are displayed without a problem.
I am trying to post to a channel id "12345". I am not sure if this might be the issue, since I am not creating the channel, but if that is the problem, how is it working if the app is in the background?
What am I missing?
I am not using Android 8, and I actually found a snippet that should be used in that case to create a channel:
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel notificationChannel = new NotificationChannel(Constants.NOTIFICATION_CHANNEL_ID, Constants.NOTIFICATION_CHANNEL_NAME, importance);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
}
Intent intent = new Intent(this, ActivityMain.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// 0 is request code
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, Constants.NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("FCM Message")
.setContentText(messageBody)
.setAutoCancel(true)
//.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// 0 is id of notification
notificationManager.notify(0, notificationBuilder.build());
My logic above had an error that I missed. The problem was in versions >= 26, because I was creating a channel and then instead of sending the notification to the correct notification manager, I was creating a new instance of the notification manager (view last 2 lines of the question code).
Here is the corrected logic:
private void sendNotification(String messageBody) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// create channel in new versions of android
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel notificationChannel = new NotificationChannel(Constants.NOTIFICATION_CHANNEL_ID, Constants.NOTIFICATION_CHANNEL_NAME, importance);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
notificationManager.createNotificationChannel(notificationChannel);
}
// show notification
Intent intent = new Intent(this, ActivityMain.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// 0 is request code
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, Constants.NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.icon_contact_purple)
.setContentTitle(getString(R.string.app_name))
.setContentText(messageBody)
.setAutoCancel(true)
//.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
// 0 is id of notification
notificationManager.notify(0, notificationBuilder.build());
}
You need to create the notification channel:
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel notificationChannel = new NotificationChannel(Constants.NOTIFICATION_CHANNEL_ID, Constants.NOTIFICATION_CHANNEL_NAME, importance);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
notificationManager.createNotificationChannel(notificationChannel);
If the Firebase Notification does not contain a data payload, Firebase automatically handles the notification when your application is in background.
That's why it is working in background.
See this reference: https://firebase.google.com/docs/cloud-messaging/android/receive

On Android 8.1 API 27 notification does not display

I get Toast on Android 8.1 API 27:
Developer warning for package "my_package_name"
Failed to post notification on ...
Logcat includes next strings:
Notification: Use of stream types is deprecated for operations other
than volume control
W/Notification: See the documentation of setSound() for what to use
instead with android.media.AudioAttributes to qualify your playback
use case
E/NotificationService: No Channel found for pkg=my_package_name
The full information in the Toast and in Logcat can help in the localization this problem.
If you get this error should be paid attention to 2 items and them order:
NotificationChannel mChannel = new NotificationChannel(id, name, importance);
builder = new NotificationCompat.Builder(context, id);
Also NotificationManager notifManager and NotificationChannel mChannel are created only once.
There are required setters for Notification:
builder.setContentTitle() // required
.setSmallIcon() // required
.setContentText() // required
See example:
private NotificationManager notifManager;
public void createNotification(String aMessage, Context context) {
final int NOTIFY_ID = 0; // ID of notification
String id = context.getString(R.string.default_notification_channel_id); // default_channel_id
String title = context.getString(R.string.default_notification_channel_title); // Default Channel
Intent intent;
PendingIntent pendingIntent;
NotificationCompat.Builder builder;
if (notifManager == null) {
notifManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = notifManager.getNotificationChannel(id);
if (mChannel == null) {
mChannel = new NotificationChannel(id, title, importance);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
notifManager.createNotificationChannel(mChannel);
}
builder = new NotificationCompat.Builder(context, id);
intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
builder.setContentTitle(aMessage) // required
.setSmallIcon(android.R.drawable.ic_popup_reminder) // required
.setContentText(context.getString(R.string.app_name)) // required
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setTicker(aMessage)
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
}
else {
builder = new NotificationCompat.Builder(context, id);
intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
builder.setContentTitle(aMessage) // required
.setSmallIcon(android.R.drawable.ic_popup_reminder) // required
.setContentText(context.getString(R.string.app_name)) // required
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setTicker(aMessage)
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
.setPriority(Notification.PRIORITY_HIGH);
}
Notification notification = builder.build();
notifManager.notify(NOTIFY_ID, notification);
}
Andy's answer is working however I wanted to avoid to deprecated Builder and follow the FireBase Quickstart Project. I just added code before notify from manager.
String channelId = "default_channel_id";
String channelDescription = "Default Channel";
// Since android Oreo notification channel is needed.
//Check if notification channel exists and if not create one
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = notificationManager.getNotificationChannel(channelId);
if (notificationChannel == null) {
int importance = NotificationManager.IMPORTANCE_HIGH; //Set the importance level
notificationChannel = new NotificationChannel(channelId, channelDescription, importance);
notificationChannel.setLightColor(Color.GREEN); //Set if it is necesssary
notificationChannel.enableVibration(true); //Set if it is necesssary
notificationManager.createNotificationChannel(notificationChannel);
}
}
//notificationManager.notify as usual
Edit:
They removed the channel exist check from example I am not sure why.
I have set channel id, but notification still not shown.
Finally i found my problem is had not invoke "setContentText()" method.
It was really help me that #Andy Sander mentioned "required setters"!
here are required setters for Notification on Android 8 Oreo API 26 and later:
builder.setContentTitle() // required
.setSmallIcon() // required
.setContentText() // required
.setChannelId(id) // required for deprecated in API level >= 26 constructor .Builder(this)
Also don't forget to bind your channel_id to your notification builder. After binding it, my problem gone.
notificationBuilder.setChannelId(channelId)
or
NotificationCompat.Builder(Context context, String channelId)

Failed to post notification on channel "null" Target Api is 26

Two log showing
1: Use of stream types is deprecated for operations other than volume control
2: See the documentation of setSound() for what to use instead with android.media.AudioAttributes to qualify your playback use case
From the developer documentation:
When you target Android 8.0 (API level 26), you must implement one or more notification channels to display notifications to your users.
int NOTIFICATION_ID = 234;
NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
String CHANNEL_ID;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
CHANNEL_ID = "my_channel_01";
CharSequence name = "my_channel";
String Description = "This is my channel";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
mChannel.setDescription(Description);
mChannel.enableLights(true);
mChannel.setLightColor(Color.RED);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
mChannel.setShowBadge(false);
notificationManager.createNotificationChannel(mChannel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx, CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(message);
Intent resultIntent = new Intent(ctx, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(ctx);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(resultPendingIntent);
notificationManager.notify(NOTIFICATION_ID, builder.build());
One interesting thing to note: If a channel already exists, calling createNotificationChannel has no effect, so you can create all channels whenever you start your application.
Gulzar Bhat's answer is working perfectly if your minimum API is Oreo. If your minimum is lower however, you have to wrap the NotificationChannel code in a platform level check. After that you can still use the id, which will be ignored pre Oreo:
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, importance);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify((int)(System.currentTimeMillis()/1000), mBuilder.build());
You can solve this in two ways but for both of them you need to create a notification channel with an specific channel id.
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String id = "my_channel_01";
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel mChannel = new NotificationChannel(id, name,importance);
mChannel.enableLights(true);
mNotificationManager.createNotificationChannel(mChannel);
First way is to set channel for notification in constructor:
Notification notification = new Notification.Builder(MainActivity.this , id).setContentTitle("Title");
mNotificationManager.notify("your_notification_id", notification);
Second way is to set the channel by Notificiation.Builder.setChannelId()
Notification notification = new Notification.Builder(MainActivity.this).setContentTitle("Title").
setChannelId(id);
mNotificationManager.notify("your_notification_id", notification);
Hope this helps
First create the notification channel:
public static final String NOTIFICATION_CHANNEL_ID = "4655";
//Notification Channel
CharSequence channelName = NOTIFICATION_CHANNEL_NAME;
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, importance);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(notificationChannel);
then use the channel id in the constructor:
final NotificationCompat.Builder builder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID)
.setDefaults(Notification.DEFAULT_ALL)
.setSmallIcon(R.drawable.ic_timers)
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
.setSound(null)
.setContent(contentView)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setLargeIcon(picture)
.setTicker(sTimer)
.setContentIntent(timerListIntent)
.setAutoCancel(false);
This issue is related to the old FCM version.
Update your dependency to
com.google.firebase:firebase-messaging:15.0.2
or higher.
This will fix the error
failed to post notification on channel null
when your app receives notifications in the background because now Firebase provides a default notification channel with basic settings.
But you also can specify the default Notification Channel for FCM in the manifest.
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="#string/default_notification_channel_id"/>
To learn more here
If you get this error should be paid attention to 2 items and them order:
NotificationChannel mChannel = new NotificationChannel(id, name, importance);
builder = new NotificationCompat.Builder(this, id);
Also NotificationManager notifManager and NotificationChannel mChannel are created only once.
There are required setters for Notification:
builder.setContentTitle() // required
.setSmallIcon() // required
.setContentText() // required
See the example in On Android 8.1 API 27 notification does not display.
I had a similar problem but starting an service as a background activity, in the service this code worked:
public static final int PRIMARY_FOREGROUND_NOTIF_SERVICE_ID = 1001;
#Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String id = "_channel_01";
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel mChannel = new NotificationChannel(id, "notification", importance);
mChannel.enableLights(true);
Notification notification = new Notification.Builder(getApplicationContext(), id)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("My chat")
.setContentText("Listening for incoming messages")
.build();
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (mNotificationManager != null) {
mNotificationManager.createNotificationChannel(mChannel);
mNotificationManager.notify(PRIMARY_FOREGROUND_NOTIF_SERVICE_ID, notification);
}
startForeground(PRIMARY_FOREGROUND_NOTIF_SERVICE_ID, notification);
}
}
It's not the best solution but just to start the service in the background It does work
String CHANNEL_ID = "my_channel";
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,CHANNEL_ID);

Categories

Resources