I want to show unread messages count on my android app's launcher icon. It should be cleared only once the user read all messages. I have tried setnumber() in NotificationCompat.Builder. But it is not showing the notification count.
I executed my code in two android devices.
Real Android device - version is 29 (red dot appeared in app launcher when i generate notification)
Android Emulator - version is 27 (nothing is shown)
Notification Channel Creation:
private void createNotificationChannel(String notificationChannelId, String systemTrayNotificationName){
Log.i("Tag","createNotificationChannel "+Build.VERSION.SDK_INT);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
CharSequence name = systemTrayNotificationName;
String description = systemTrayNotificationName;
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(notificationChannelId, name,importance);
notificationChannel.setDescription(description);
notificationChannel.setShowBadge(true);
notificationChannel.canShowBadge();
NotificationManager notificationManager = getContext().getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(notificationChannel);
}
}
Code to form notification
public void buildNotification(){
createNotificationChannel(NOTIFICATION_CHANNEL_ID,SYSTEM_TRAY_NOTIFICATION_NAME);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getContext(), NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_home_black_24dp)
.setLargeIcon(BitmapFactory.decodeResource(getContext().getResources(), R.mipmap.ic_launcher))
.setContentTitle("Title")
.setContentText("Content Text")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setNumber(5)
.setBadgeIconType(NotificationCompat.BADGE_ICON_NONE)
.setAutoCancel(true);
// Get an instance of the NotificationManager service
NotificationManagerCompat notificationManager =
NotificationManagerCompat.from(getContext());
// Issue the notification with notification manager.
notificationManager.notify(200, notificationBuilder.build());
}
The number of notifications must be supported by the launcher you are using.
As far as I know, the pixel launcher typical of google phones and present by default as launcher3 of the emulators does not support the notification count exactly as it happens in your first case.
You could try with a third party launcher to see if the counting works but as just said this feature must be natively supported by the launcher.
I start a foreground service that shows up in the status bar under android systems battery information.
Is there a way to customize the information (title, subtext, icon, ...) presented?
service code: CODE EDITED
#Override
public void onCreate() {
context = this.getApplicationContext();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Intent notificationIntent = new Intent(context, CallbackTestWidgetService.class);
PendingIntent pendingIntent =
PendingIntent.getActivity(context, 10, notificationIntent, 0);
Notification notification = new Notification.Builder(context, "Test")
.setContentTitle("Test")
.setContentText("text")
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.test)
.setTicker("test")
.build();
CharSequence name = "test";
String description = "test";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel("10", name, importance);
channel.setDescription("test");
// 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);
startForeground(10, notification);
}
}
What you're seeing is the default notification when no notification is posted by the app.
The reason why no notification is being posted (despite you calling startForeground) is that you are targeting API 26 or higher and not associating your notification with a notification channel. This causes your notification to be dropped entirely as per the note on that page:
Caution: If you target Android 8.0 (API level 26) and post a notification without specifying a notification channel, the notification does not appear and the system logs an error.
You must create a notification channel, then include the id of the notification channel when building your notification.
You're building a Notification to pass to startForeground. Use the createContentView function, just like you would for a normal notification you wanted to customize.
Note that this will only work on newer versions of Android, you probably want to use the NotiicationCompat class from the support library to support version specific api differences and test on a few different APIs of emulators.
Maybe this issue is way simpler than I expected it to be: I want to display a notification, created within the onCreate function of an Activity (for debugging reasons).
Android Studio 3.0.1, Api lvl 23 (to support older devices) and running on a Nexus5 device with Api lvl 27.
The Code to display a notification:
PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
Notification notification = new NotificationCompat.Builder(this)
.setTicker("SomethingTicker")
.setSmallIcon(R.drawable.someImage)
.setContentTitle("SomeTitle")
.setContentText("SomeText")
.setContentIntent(pi)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(001, notification);
Which shows that NotificationCompat.Builder with only the the context is deprecated. I should use a Notification Channel within the newer version.
The issue: To create and register a NotificationChannel I have to use api lvl >27.
What am I missing? And what is the best way
I want to display a notification, created within the onCreate function of an Activity.
Note that this is an odd time to display a Notification.
What am I missing?
You need code to create the NotificationChannel that will only run on Android 8.0+ devices:
NotificationManager mgr=
(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O &&
mgr.getNotificationChannel(CHANNEL_WHATEVER)==null) {
mgr.createNotificationChannel(new NotificationChannel(CHANNEL_WHATEVER,
"Whatever", NotificationManager.IMPORTANCE_DEFAULT));
}
Then, for all API levels, pass in your channel identifier (here, CHANNEL_WHATEVER) to the NotificationCompat.Builder constructor. On older devices, the channel will be ignored.
With the below code my notification are only added to the notification bar, no popup style message is displayed like if you would receive a whatsapp message when you're in another application. What makes that happen to a notification?
private void sendNotification(int distance, ViewObject viewObject) {
Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
notificationIntent.putExtra("path", viewObject.getPath());
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(notificationIntent);
PendingIntent notificationPendingIntent = stackBuilder.getPendingIntent(Integer.parseInt(viewObject.getRefId()), PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
bigText.bigText(String.format(getString(R.string.notification), viewObject.getTitle()));
bigText.setBigContentTitle(getString(R.string.hello));
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(R.drawable.ic_wald_poi)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_poi))
.setColor(getResources().getColor(R.color.primary))
.setContentTitle(getString(R.string.hello))
.setContentIntent(notificationPendingIntent)
.setContentText(String.format(getString(R.string.notification), viewObject.getTitle()))
.setDefaults(Notification.DEFAULT_ALL)
.setStyle(bigText);
builder.setAutoCancel(true);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0, builder.build());
}
If you want use Heads-up Notifications like this:
You must change Notification priority or NotificationChannel importance.
The notification priority, set by setPriority(). The priority determines how intrusive the notification should be on Android 7.1 and lower. (For Android 8.0 and higher, you must instead set the channel importance)
On Android 7.1 (API level 25) and lower:
Set notification priority to NotificationCompat.PRIORITY_HIGH or NotificationCompat.PRIORITY_MAX.
Set ringtone and vibrations - you can use setDefaults(Notification.DEFAULT_ALL)
Android 8.0 (API level 26) and higher:
Set notification channel priority to NotificationManager.IMPORTANCE_HIGH
Notification:
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(R.drawable.ic_wald_poi)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_poi))
.setColor(getResources().getColor(R.color.primary))
.setContentTitle(getString(R.string.hello))
.setContentIntent(notificationPendingIntent)
.setContentText(String.format(getString(R.string.notification), viewObject.getTitle()))
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setStyle(bigText)
.setPriority(NotificationCompat.PRIORITY_HIGH) // or NotificationCompat.PRIORITY_MAX
Notification channel:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Create the NotificationChannel
val name = getString(R.string.notification_channel_name)
val descriptionText = getString(R.string.notification_channel_description)
val importance = NotificationManager.IMPORTANCE_HIGH
val mChannel = NotificationChannel(NOTIFICATION_CHANNEL_ID, name, importance)
mChannel.description = descriptionText
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(mChannel)
}
Important
If you'd like to further customize your channel's default notification behaviors, you can call methods such as enableLights(), setLightColor(), and setVibrationPattern() on the NotificationChannel. But remember that once you create the channel, you cannot change these settings and the user has final control of whether these behaviors are active. Other option is to uninstall and install application again.
Read more
Examples of conditions that may trigger heads-up notifications include:
The user's activity is in fullscreen mode (the app uses
fullScreenIntent).
The notification has high priority and uses
ringtones or vibrations on devices running Android 7.1 (API level 25)
and lower.
The notification channel has high importance on devices
running Android 8.0 (API level 26) and higher.
Priority:
Notification.PRIORITY_HIGH and Notification.PRIORITY_MAX was deprecated in API level 26. use NotificationCompat instead.
Here is more info :-)
You have to set the notification priority to Notification.PRIORITY_HIGH or Notification.PRIORITY_MAX. I had to also do .setDefaults(Notification.DEFAULT_ALL).
Below API level 26:
Set Notification.PRIORITY_HIGH or Notification.PRIORITY_MAX in the Builder when sending the message.
API level 26 or above:
Set channel priority high
Important:
Once the channel has a established priority it cannot be changed. If it was in LOW will not show the popup, unless you reinstall the APP.
The Android system is deciding wheter a notification is displayed as Heads-up notification. There are several conditions which may trigger a Heads-up notification:
Examples of conditions that may trigger heads-up notifications include:
The user's activity is in fullscreen mode (the app uses fullScreenIntent).
The notification has high priority and uses ringtones or vibrations on devices running Android 7.1 (API level 25) and lower.
The notification channel has high importance on devices running Android 8.0 (API level 26) and higher.
Source: https://developer.android.com/guide/topics/ui/notifiers/notifications.html#Heads-up
So if you're running Android 7.1 and lower, be sure to add a ringtone or vibration as well as the high priority. For Android 8.0 and higher, change the priority to high importance.
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
// ...
.setDefaults(DEFAULT_SOUND | DEFAULT_VIBRATE)
.setPriority(NotificationCompat.PRIORITY_HIGH); // or HIGH_IMPORTANCE for Android 8.0
I need a program that will add a notification on Android. And when someone clicks on the notification, it should lead them to my second activity.
I have established code. The notification should be working, but for some reason it is not working. The Notification isn't showing at all. I don't know what am I missing.
Code of those files:
Notification n = new Notification.Builder(this)
.setContentTitle("New mail from " + "test#gmail.com")
.setContentText("Subject")
.setContentIntent(pIntent).setAutoCancel(true)
.setStyle(new Notification.BigTextStyle().bigText(longText))
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Hide the notification after it's selected
notificationManager.notify(0, n);
The code won't work without an icon. So, add the setSmallIcon call to the builder chain like this for it to work:
.setSmallIcon(R.drawable.icon)
Android Oreo (8.0) and above
Android 8 introduced a new requirement of setting the channelId property by using a NotificationChannel.
NotificationManager mNotificationManager;
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(mContext.getApplicationContext(), "notify_001");
Intent ii = new Intent(mContext.getApplicationContext(), RootActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, ii, 0);
NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
bigText.bigText(verseurl);
bigText.setBigContentTitle("Today's Bible Verse");
bigText.setSummaryText("Text in detail");
mBuilder.setContentIntent(pendingIntent);
mBuilder.setSmallIcon(R.mipmap.ic_launcher_round);
mBuilder.setContentTitle("Your Title");
mBuilder.setContentText("Your text");
mBuilder.setPriority(Notification.PRIORITY_MAX);
mBuilder.setStyle(bigText);
mNotificationManager =
(NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
// === Removed some obsoletes
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
String channelId = "Your_channel_id";
NotificationChannel channel = new NotificationChannel(
channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_HIGH);
mNotificationManager.createNotificationChannel(channel);
mBuilder.setChannelId(channelId);
}
mNotificationManager.notify(0, mBuilder.build());
Actually the answer by Ć’ernando Valle doesn't seem to be correct. Then again, your question is overly vague because you fail to mention what is wrong or isn't working.
Looking at your code I am assuming the Notification simply isn't showing.
Your notification is not showing, because you didn't provide an icon. Even though the SDK documentation doesn't mention it being required, it is in fact very much so and your Notification will not show without one.
addAction is only available since 4.1. Prior to that you would use the PendingIntent to launch an Activity. You seem to specify a PendingIntent, so your problem lies elsewhere. Logically, one must conclude it's the missing icon.
You were missing the small icon.
I did the same mistake and the above step resolved it.
As per the official documentation:
A Notification object must contain the following:
A small icon, set by setSmallIcon()
A title, set by setContentTitle()
Detail text, set by setContentText()
On Android 8.0 (API level 26) and higher, a valid notification channel ID, set by setChannelId() or provided in the NotificationCompat.Builder constructor when creating a channel.
See http://developer.android.com/guide/topics/ui/notifiers/notifications.html
This tripped me up today, but I realized it was because on Android 9.0 (Pie), Do Not Disturb by default also hides all notifications, rather than just silencing them like in Android 8.1 (Oreo) and before. This doesn't apply to notifications.
I like having DND on for my development device, so going into the DND settings and changing the setting to simply silence the notifications (but not hide them) fixed it for me.
Creation of notification channels are compulsory for Android versions after Android 8.1 (Oreo) for making notifications visible. If notifications are not visible in your app for Oreo+ Androids, you need to call the following function when your app starts -
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name,
importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviours after this
NotificationManager notificationManager =
getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
You also need to change the build.gradle file, and add the used Android SDK version into it:
implementation 'com.android.support:appcompat-v7:28.0.0'
This worked like a charm in my case.
I think that you forget the
addAction(int icon, CharSequence title, PendingIntent intent)
Look here: Add Action
I had the same issue with my Android app. I was trying out notifications and found that notifications were showing on my Android emulator which ran a Android 7.0 (Nougat) system, whereas it wasn't running on my phone which had Android 8.1 (Oreo).
After reading the documentation, I found that Android had a feature called notification channel, without which notifications won't show up on Oreo devices. Below is the link to official Android documentation on notification channels.
Notifications Overview, Notification anatomy
Create and Manage Notification Channels
For me it was an issue with deviceToken. Please check if the receiver and sender device token is properly updated in your database or wherever you are accessing it to send notifications.
For instance, use the following to update the device token on app launch. Therefore it will be always updated properly.
// Device token for push notifications
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(
new OnSuccessListener<InstanceIdResult>() {
#Override
public void onSuccess(InstanceIdResult instanceIdResult) {
deviceToken = instanceIdResult.getToken();
// Insert device token into Firebase database
fbDbRefRoot.child("user_detail_profile").child(currentUserId).child("device_token")).setValue(deviceToken)
.addOnSuccessListener(
new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
});
}
});
I encountered a similar problem to yours and while searching for a solution I found these answers but they weren't as direct as I hoped they would be but it gives an Idea; Your notifications may not be showing because for versions >=8 notifications are done relatively differently there is a NotificationChannel which aids in managing notifications this helped me. Happy coding.
void Note(){
//Creating a notification channel
NotificationChannel channel=new NotificationChannel("channel1",
"hello",
NotificationManager.IMPORTANCE_HIGH);
NotificationManager manager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.createNotificationChannel(channel);
//Creating the notification object
NotificationCompat.Builder notification=new NotificationCompat.Builder(this,"channel1");
//notification.setAutoCancel(true);
notification.setContentTitle("Hi this is a notification");
notification.setContentText("Hello you");
notification.setSmallIcon(R.drawable.ic_launcher_foreground);
//make the notification manager to issue a notification on the notification's channel
manager.notify(121,notification.build());
}
Make sure your notificationId is unique. I couldn't figure out why my test pushes weren't showing up, but it's because the notification ids were generated based on the push content, and since I was pushing the same notification over and over again, the notification id remained the same.
Notifications may not be shown if you show the notifications rapidly one after the other or cancel an existing one, then right away show it again (e.g. to trigger a heads-up-notification to notify the user about a change in an ongoing notification). In these cases the system may decide to just block the notification when it feels they might become too overwhelming/spammy for the user.
Please note, that at least on stock Android (tested with 10) from the outside this behavior looks a bit random: it just sometimes happens and sometimes it doesn't. My guess is, there is a very short time threshold during which you are not allowed to send too many notifications. Calling NotificationManager.cancel() and then NotificationManager.notify() might then sometimes cause this behavior.
If you have the option, when updating a notification don't cancel it before, but just call NotificationManager.notify() with the updated notification. This doesn't seem to trigger the aforementioned blocking by the system.
If you are on version >= Android 8.1 (Oreo) while using a Notification channel, set its importance to high:
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
val pendingIntent = PendingIntent.getActivity(applicationContext, 0, Intent(), 0)
var notification = NotificationCompat.Builder(applicationContext, CHANNEL_ID)
.setContentTitle("Title")
.setContentText("Text")
.setSmallIcon(R.drawable.icon)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent)
.build()
val mNotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
mNotificationManager.notify(sameId, notification)