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.
Related
startForeground() need to create NotificationChannel so it will show badge number 1 on Launcher icon in Oreo devices
How can i hide/disable it programmatically?
Because Galaxy S8(Oreo) display badge number 1.
And Android 8.0 emulator also display dot.
This is how i am doing now. But setShowBadge(false) not works
EDIT1:
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationChannel tmpC = new NotificationChannel(id, "basic", NotificationManager.IMPORTANCE_MIN);
tmpC.setShowBadge(false);
manager.createNotificationChannel(tmpC);
Notification notification = new NotificationCompat.Builder(this, id)
.setChannelId(id)
.setAutoCancel(true)
.build();
startForeground(getPackageName().hashCode(), notification);
This answer is correct, but the point is you have to remove old version of the application by hands from Android "Applications" menu and install new version with mChannel.setShowBadge(false) on the clean device to get it working. An installation over the old version (where mChannel.setShowBadge(false) was absent) will not lead to the changing of the behaviour concerned with this badge.
all you need to do is calling setShowBadge(false) on your NotificationChannel object.
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Create notification channel.
NotificationChannel channel = new NotificationChannel({channel_id}, {name}, {importance});
mChannel.setShowBadge(false); // Disable badges for this notification channel.
mNotificationManager.createNotificationChannel(mChannel);
// Create notification and use channel
Notification notification = new NotificationCompat.Builder(context, {channel_id})
...
.build();
// notify
mNotificationManager.notify({notification_id}, notification)
Check out Modify a Notification Badge.
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Example Service Channel",
NotificationManager.IMPORTANCE_MIN
);
serviceChannel.setVibrationPattern(new long[]{ 0 });
serviceChannel.enableVibration(true);
serviceChannel.enableLights(false);
serviceChannel.setSound(null, null);
serviceChannel.setShowBadge(false); //
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
setShowBadge(false) it is working
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
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)
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);
I recently updated my app to API 26, and notifications are no longer working, without even changing the code.
val notification = NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("Title")
.setContentText("Text")
.build()
(getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).notify(1, notification)
Why isn't it working? Was there some change to the API that I'm not aware of?
From the documentation:
Android O introduces notification channels to provide a unified system to help users manage notifications. When you target Android O, you must implement one or more notification channels to display notifications to your users. If you don't target Android O, your apps behave the same as they do on Android 7.0 when running on Android O devices.
(emphasis added)
You do not seem to be associating this Notification with a channel.
Here i post some quick solution
public void notification(String title, String message, Context context) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
int notificationId = createID();
String channelId = "channel-id";
String channelName = "Channel Name";
int importance = NotificationManager.IMPORTANCE_HIGH;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(
channelId, channelName, importance);
notificationManager.createNotificationChannel(mChannel);
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.app_logo)//R.mipmap.ic_launcher
.setContentTitle(title)
.setContentText(message)
.setVibrate(new long[]{100, 250})
.setLights(Color.YELLOW, 500, 5000)
.setAutoCancel(true)
.setColor(ContextCompat.getColor(context, R.color.colorPrimary));
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addNextIntent(new Intent(context, MainAcivity.class));
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
notificationManager.notify(notificationId, mBuilder.build());
}
public int createID() {
Date now = new Date();
int id = Integer.parseInt(new SimpleDateFormat("ddHHmmss", Locale.FRENCH).format(now));
return id;
}