Custom notification sound not working in 5.0 and higher - android

I am trying to add custom sound to notification. Following is my code:
notificationSoundUri = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.error);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("default",
"YOUR_CHANNEL_NAME",
NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("YOUR_NOTIFICATION_CHANNEL_DISCRIPTION");
mNotificationManager.createNotificationChannel(channel);
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, "default")
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
.setSmallIcon(R.mipmap.ic_launcher) // notification icon
.setContentTitle("BATTERY FULL") // title for notification
.setContentText("Battery is full. Please plug out the charger. Overcharging may decrease battery life span.")// message for notification
.setSound(notificationSoundUri) // set alarm sound for notification
.setAutoCancel(true); // clear notification after click
mNotificationManager.notify(1, mBuilder.build());
This code is working in pre-lollipop devices and not on Marshmallow. In Marshmallow, it is using phone's default notification sound. I am assuming this problem is for lollipop and higher devices. What am I missing here?

Had this issue for a few tries, it looks like NotificationCompat misses a method for sound on between androids 21 and 25, for notification to work you need to set the sound as this
val builder: Notification.Builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Notification.Builder(this, channelId1)
} else {
Notification.Builder(this)
}
...
val audioAttr = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_ALARM).build()
builder.setSound(
notification1Sound(), // custom uri
audioAttr)
I don't support versions prior lollipop so this works for me, for older version you might need to add a second version check
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder.setSound(
notification1Sound(),
audioAttr
)
} else {
builder.setSound(notification1Sound(), AudioManager.STREAM_ALARM)
}

You have to use Notification Channel whit Android O (https://developer.android.com/training/notify-user/channels).
This work only on API 26+ because the NotificationChannel class is new and not in the support library.

builder.setStyle(new NotificationCompat.InboxStyle());
The full code:
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Notifications Example")
.setContentText("This is a test notification");
Intent notificationIntent = new Intent(this, MenuScreen.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
builder.setAutoCancel(true);
builder.setLights(Color.BLUE, 500, 500);
long[] pattern = {500,500,500,500,500,500,500,500,500};
builder.setVibrate(pattern);
builder.setStyle(new NotificationCompat.InboxStyle());
Use these lines of code for custom sound
URI uri=Uri.parse("android.resource://"+context.getPackageName()+"/"+R.raw.FILE_NAME);//Here is FILE_NAME is the name of file that you want to play
builder.setSound(uri);
Don't forget to add notification channel
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
#SuppressLint("WrongConstant")
NotificationChannel channel = new NotificationChannel("XYZ", "ABC",NotificationManager.IMPORTANCE_MAX);
mNotificationManager.createNotificationChannel(channel);
}
mNotificationManager.notify(0, mBuilder.build());

Related

Android Default Notification sound not working

I can see on MI phone android version 10. i am trying to create a simple notification with title and subtitle. notification also shows up but with no sound and no vibration.
PFB the code:
Intent intent = new Intent(this, MyActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = getString(R.string.default_notification_channel_id);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_CALL)
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
.setContentIntent(pendingIntent);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
notificationBuilder.setSmallIcon(R.drawable.app_icon_white);
notificationBuilder.setColor(getResources().getColor(R.color.theme_color));
} else {
notificationBuilder.setSmallIcon(R.drawable.app_icon_white);
}
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_HIGH);
CharSequence name = getResources().getString(R.string.feroz_channel_name);
String description = getResources().getString(R.string.feroz_channel_description);
channel.enableLights(true);
channel.setLightColor(getResources().getColor(R.color.theme_color));
channel.enableVibration(true);
channel.setDescription(description);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(77 /* ID of notification */, notificationBuilder.build());
I have vibration permission in Android Manifest. Along with no sound and no vibration. this notification is not visible when device is in locked state. Please suggest what i have missed in the code to achieve this scenario on android 10.

Notifications always making sound: setSound(null) is not wroking on OS >= 8

I am trying to group notifications and trigger sounds only for some of them using notification builder setSound() method, but it doesn't work. Each time I receive notifications it triggers the ringtone even though I call setSound(null)
This is my code:
TaskStackBuilder stackBuilder = TaskStackBuilder.create(getContext());
stackBuilder.addParentStack(getParentActivityClass());
Intent notificationIntent = intent == null ? new Intent() : new Intent(intent);
if (cls != null)
notificationIntent.setClass(getContext(), cls);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
stackBuilder.addNextIntentWithParentStack(notificationIntent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT);
InboxStyle style = new NotificationCompat.InboxStyle();
int mapId = subGroupId + groupId;
putGroupLine(mapId, text);
List<String> notifLines = groupedNotificationsMap.get(mapId);
for (int i = 0; i < notifLines.size(); i++) {
style.addLine(notifLines.get(i));
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String NOTIFICATION_CHANNEL_ID = "default";
String channelName = "Default";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName
, NotificationManager.IMPORTANCE_HIGH);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
if (alert == false) {
chan.setSound(null, null);
chan.setVibrationPattern(null);
}
else {
chan.setVibrationPattern(vibrate);
}
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.createNotificationChannel(chan);
}
NotificationCompat.Builder mBuilder;
mBuilder = new NotificationCompat.Builder(context, "default")
.setSmallIcon(getSmallIconResource())
.setAutoCancel(true);
int colorRes = getSmallIconColor();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mBuilder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_SUMMARY);
}
if (alert) {
mBuilder.setSound(getRingtone());
mBuilder.setVibrate( vibrate );
}
else {
mBuilder.setSound(null);
mBuilder.setVibrate(null);
}
Notification notif = mBuilder
.setContentTitle(title)
.setTicker(text)
.setContentText(text)
.setSmallIcon(getSmallIconResource())
.setStyle(style
.setBigContentTitle(title)
)
.setGroup("g" + groupId)
.setContentIntent(pendingIntent)
.build();
NotificationCompat.Builder summaryBiulder = new NotificationCompat.Builder(getContext(), "default")
.setContentTitle(title)
.setAutoCancel(true)
//set content text to support devices running API level < 24
.setContentText(text)
.setSmallIcon(getSmallIconResource())
//build summary info into InboxStyle template
.setStyle(new InboxStyle()
.setBigContentTitle(title)
.setSummaryText(title))
.setColor(colorRes)
//specify which group this notification belongs to
.setGroup("g" + groupId)
//set this notification as the summary for the group
.setGroupSummary(true)
.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_SUMMARY)
.setContentIntent(pendingIntent);
if (alert) {
summaryBiulder.setSound(getRingtone());
summaryBiulder.setVibrate( vibrate );
}
else {
summaryBiulder.setSound(null);
summaryBiulder.setVibrate(null);
}
Notification summaryNotification = summaryBiulder .build();
notif.flags |= Notification.FLAG_AUTO_CANCEL;
notif.flags |= Notification.FLAG_HIGH_PRIORITY;
notifManager.notify(subGroupId, notif);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notifManager.notify(groupId, summaryNotification);
}
Any suggestions?
Your problem is about notification importance
importance types
IMPORTANCE_MAX: unused
IMPORTANCE_HIGH: shows everywhere, makes noise and peeks
IMPORTANCE_DEFAULT: shows everywhere, makes noise, but does not visually intrude
IMPORTANCE_LOW: shows everywhere, but is not intrusive
IMPORTANCE_MIN: only shows in the shade, below the fold
IMPORTANCE_NONE: a notification with no importance; does not show in the shade
source
Although the other answers are useful, the main issue here was that the notification channel was already created. So, as stated in the docs, the behavior of a channel cannot be changed after creation (sound and vibration in this case). Only name and description can be changed, the user has full control over the rest.
In the code snippet,
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName,
NotificationManager.IMPORTANCE_HIGH);
Try replacing
NotificationManager.IMPORTANCE_HIGH to NotificationManager.IMPORTANCE_NONE
As according to Android developer documentation,
IMPORTANCE_HIGH
Higher notification importance: shows everywhere, makes noise and peeks. May use full screen intents.
So it may be making sound due to this.
Here's the link to other importance values available

Notification setSound() doesn't seem to actually set a sound

I recently started coding my first android project including notifications (SDK 21 - Android 5)
Currently, I have a tiny little button, that creates a notification on click and sends it to the app itself. Sound foolish but the purpose is to test if a custom sound and vibrate pattern is used.
This is the notification that gets constructed on click:
Notification note = new Notification.Builder(this.requireContext(), "channel_id")
.setSmallIcon(R.mipmap.icon)
.setContentTitle("Title")
.setContentText("Text")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setVibrate(new long[] {500, 500, 500, 500, 500})
.setSound(SettingsHandler.getRingtoneUri(this.requireContext())
.setContentIntent(anyIntent)
.setAutoCancel(true)
.build();
SettingsHandler is a helper class I created to handle settings. Like switching vibration on and off or picking a ringtone. getRingtoneUri() does the following:
public synchronized static Uri getRingtoneUri(Context context) {
SharedPreferences prefs = context.getSharedPreferences("table_name", Context.MODE_PRIVATE);
return Uri.parse(prefs.getString("ringtone_uri_key", RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION).toString()));
}
When debugging this the result of getRingtoneUri is something like "content://media/internal/audio/media/31". This looks valid to me. However, in a later line, the sound property of the created notification is still null. Amy idea what I'm doing wrong? Thanks in forward.
try this:
Uri alarmSound = Uri.parse("android.resource://" + context.getPackageName() + "/raw/ding");
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, context.getString(R.string.checkout_channel));
mBuilder.setContentTitle(context.getString(R.string.passenger_name)).setContentText(context.getString(R.string.pit, name)).setSmallIcon(R.drawable.notification_icon).setSound(alarmSound);
Notification notification = mBuilder.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
String channelDescription = "Checkout Channel";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build();
NotificationChannel notificationChannel = new NotificationChannel(context.getString(R.string.checkout_channel),
channelDescription, notifManager.IMPORTANCE_HIGH);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.GREEN);
notificationChannel.setShowBadge(true);
notificationChannel.setSound(alarmSound, audioAttributes);
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
notificationManager.createNotificationChannel(notificationChannel);
}
notificationManager.notify(iUniqueId, notification);
You need to set the audioAttributes and create your notification channel. This works for me for all Android from 4.2 to 9

Enable Sound button in Notification Channel

In MI Note 5 Pro which has latest MI UI 10.0 with Oreo, so when I try to send push notification by default sound is disable, so i am not able to enable sound programmatically when I am creating a channel for that.
In other Oreo devices notification sound is coming but in MI custom Oreo OS Sound is by default disable
Let me show my code for notification :
var intent = Intent(mContext, HomeActivity::class.java)
intent.putExtra(Constants.EXTRA_FROM_NOTIFICATION, true)
var pendingIntent = PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
var uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
var mBuilder = NotificationCompat.Builder(mContext, NOTIFICATION_CHANNEL_ID)
.setContentTitle(mContext.getString(R.string.app_name))
.setContentText(mFirstContactName + " : " + mListChatWindow[0].message)
.setPriority(if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) NotificationManager.IMPORTANCE_HIGH else Notification.PRIORITY_HIGH)
.setContentIntent(pendingIntent)
.setSound(uri)
.setSmallIcon(R.drawable.ic_app_icon)
.setColor(ContextCompat.getColor(mContext, R.color.colorPrimary))
.setVibrate(longArrayOf(0, 100, 1000, 300))
.setAutoCancel(true)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
var channel = NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", NotificationManager.IMPORTANCE_HIGH)
channel.description = "NOTIFICATION_DESCRIPTION"
channel.lightColor = Color.LTGRAY
channel.enableVibration(true)
channel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
val attributes = AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_NOTIFICATION).build()
channel.setSound(uri, attributes)
var notificationManager = mContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
var notificationManager = NotificationManagerCompat.from(mContext)
notificationManager.notify(NOTIFICATION_CHAT_ID, mBuilder.build())
I am also set channel.setSound(uri, attributes) in cannel but sound not coming
Here is the screenshot of Notification channel see there sound icon is disabled, how to enable?
Plz help
I had similar problem in MIUI Global 10.1 with oreo but it was only while using custom sound and not like yours, default sound. Any way let me explain how I solve it and hope it may solve yours.
First thing to consider is where the registration of notification channel is executed. It must be executed in Application.onCreate so that the channel is created even before the notification arrives. I was doing it in onMessageReceived.
Second as I said it was working for default notification sound and not for custom one, I inserted below code while creating notification channel and it worked.
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,CHANNEL_ID);
if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.O) {
notificationBuilder.setDefaults(Notification.DEFAULT_SOUND); // This line did the magic for me.
Uri sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.sound_notification_plucky);
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
CharSequence name = "MyChild";
String description = "All MyChild messages";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, name, importance);
notificationChannel.setDescription(description);
notificationChannel.enableVibration(true);
notificationChannel.setSound(sound, audioAttributes);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(notificationChannel);
}
I'm facing same issue and still didn't get satisfying answer, but till that time we can workaround it like so:
final Uri NOTIFICATION_SOUND = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
RingtoneManager.getRingtone(context, NOTIFICATION_SOUND).play();
You need to call this after:
notificationManager.notify(notificationId, notification);
This way you will always get sound playing even if "allow sound" was turned off for your App, and the sound played will be from the system not media (expected behavior from the notifications).
And to avoid having two sounds playing at once (for the devices that don't have this issue), you can turn the sounds off like so:
1- For the Builder:
notificationBuilder.setContentTitle(title)
.set.....
.set.....
.setSound(null);
2- For the channel:
channel.setSound(null, null);
mBuilder.setPriority(NotificationCompat.PRIORITY_HIGH)
This line of code is worked for me it enables all notification settings.

Android O reporting notification not posted to channel - but it is

Couple Android O notification questions:
1) I have created a Notification Channel (see below), am calling the builder with .setChannelId() (passing in the name of the channel I created, "wakey"; and yet, when I run the app, I get a message that I've failed to post a notification to channel "null". What might be causing this?
2) I suspect the answer to #1 can be found in the "log" that it says to check, but I've checked logcat & don't see anything about notifications or channels. Where is the log that it says to look in?
Here's the code I'm using to create the channel:
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence name = context.getString(R.string.app_name);
String description = "yadda yadda"
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL, name, importance);
channel.setDescription(description);
notificationManager.createNotificationChannel(channel);
Here's the code to generate the notification:
Notification.Builder notificationBuilder;
Intent notificationIntent = new Intent(context, BulbActivity.class);
notificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); // Fix for https://code.google.com/p/android/issues/detail?id=53313
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
Intent serviceIntent = new Intent(context, RemoteViewToggleService.class);
serviceIntent.putExtra(WakeyService.KEY_REQUEST_SOURCE, WakeyService.REQUEST_SOURCE_NOTIFICATION);
PendingIntent actionPendingIntent = PendingIntent.getService(context, 0, serviceIntent, PendingIntent.FLAG_CANCEL_CURRENT);
_toggleAction = new Notification.Action(R.drawable.ic_power_settings_new_black_24dp, context.getString(R.string.toggle_wakey), actionPendingIntent);
notificationBuilder= new Notification.Builder(context)
.setContentTitle(context.getString(R.string.app_name))
.setContentIntent(contentIntent)
.addAction(_toggleAction);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
notificationBuilder.setChannelId(NOTIFICATION_CHANNEL);
}
notificationBuilder.setSmallIcon(icon);
notificationBuilder.setContentText(contentText);
_toggleAction.title = actionText;
int priority = getNotificationPriority(context);
notificationBuilder.setPriority(priority);
notificationBuilder.setOngoing(true);
Notification notification = notificationBuilder.build();
notificationManager.notify(NOTIFICATION_ID, notification);
And here's the warning I'm getting:
I think I have learned a couple things that all add up to an answer:
I was using an emulator device, with an image that did not include the Play Store.
The version of Google Play Services on the image was not the latest, so I should have been getting a notification telling me I needed to upgrade. Since that notification didn't get applied to a channel, it didn't appear.
If I set logcat in Android Studio to "No Filters" instead of "Show only selected application", then I found the logs that pointed out that the notification in question was the Play Services "update needed" notification.
So, I changed to a image with the Play Store included, and it showed the notification properly (maybe the channel for that notification was to be set by the Play Store?), let me update to the latest Google Play Services, and I haven't seen that warning since.
So, long story short (too late) - with Android O, if you are using Google Play Services & testing on the emulator, choose an image with the Play Store included, or ignore the toast (good luck on that one!).
I had the same problem, and resolved it by using the constructor
new Notification.Builder(Context context, String channelId), instead of the one which is deprecated onAPI levels >=26 (Android O) :
new NotificationCompat.Builder(Context context)
The following code won't work if your notificationBuilder is built using the deprecated constructor :
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
notificationBuilder.setChannelId(NOTIFICATION_CHANNEL);}
First create the notification channel:
public static final String NOTIFICATION_CHANNEL_ID = "4565";
//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)
.setChannelId(NOTIFICATION_CHANNEL_ID)
.setContent(contentView)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setLargeIcon(picture)
.setTicker(sTimer)
.setContentIntent(pendingIntent)
.setAutoCancel(false);
You gotta create a channel before.
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 behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
public void notifyThis(String title, String message) {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.green_circle)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
// notificationId is a unique int for each notification that you must define
notificationManager.notify(0, mBuilder.build());
}
Finally you call this method:
createNotificationChannel();
notifyThis("My notification", "Hello World!");
create a notification using following code :
Notification notification = new Notification.Builder(MainActivity.this)
.setContentTitle("New Message")
.setContentText("You've received new messages.")
.setSmallIcon(R.mipmap.ic_launcher)
.setChannelId(channelId)
.build();
not using :
Notification notification = new NotificationCompat.Builder(MainActivity.this)
.setContentTitle("Some Message")
.setContentText("You've received new messages!")
.setSmallIcon(R.mipmap.ic_launcher)
.setChannel(channelId)
.build();
You have to create a NotificationChannel first
val notificationChannel = NotificationChannel("channelId", "channelName", NotificationManager.IMPORTANCE_DEFAULT)
notificationManager.createNotificationChannel(notificationChannel);
This is the only way to show notification for API 26+
I was facing the same problem. It got resolved by creating a NotificationChannel and adding that newly created channel with the notification manager.
I would also like to add that you will receive this error if you're using Build tools v26+:
app/build.grade:
compileSdkVersion 26
buildToolsVersion "26.0.2"
defaultConfig {
targetSdkVersion 26
Downgrading to lowest version should work fine.

Categories

Resources