Application icon badge not displayed Android - android

For an assignment, I have to write an application which can display all contacts and their birthday date (& create / modify them). So far so good. Then, I have to fire a notification with all people who are born today.
The notification is launched without problem but I don't get the app icon badge.
After searching, I found out I have to use the channels -> done.
I've verified in the settings if the notification dot is enabled:
I've verified the android documentation saying "it's automatic you shoundn't have anything to do"
My simulator is using Android 9.0 which is greater than android oreo.
So what's wrong ?
public class BirthdayListener implements View.OnClickListener {
private static final String CHANNEL_ID = "ch.hefr.tic.birthday_channel";
private static final int SUMMARY_ID = -1;
private static final String GROUP_KEY = "ch.hefr.tic.group_channel";
private Context context;
private NotificationManager notificationManager;
public BirthdayListener(Context context) {
this.context = context;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = context.getResources().getString(R.string.channel_name);
String description = context.getResources().getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
channel.setShowBadge(true);
notificationManager = context.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
#Override
public void onClick(View v) {
List<Contact> hasBirthday = searchBirthdays();
NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context);
NotificationCompat.InboxStyle summaryStyle = new NotificationCompat.InboxStyle();
summaryStyle.setBigContentTitle(hasBirthday.size() + " new messages");
for(int i = 0; i < hasBirthday.size(); ++i) {
Contact contact = hasBirthday.get(i);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_notification)
.setContentTitle("Birthday")
.setContentText(contact.getName() + " has his birthday today !")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setGroup(GROUP_KEY)
.setNumber(5);
String phoneNumber = contact.getPhoneNumber();
if(phoneNumber != null && !phoneNumber.equals("")) {
Intent smsIntent = new Intent(Intent.ACTION_VIEW);
smsIntent.setData(Uri.parse("sms:" + phoneNumber));
PendingIntent pending = PendingIntent.getActivity(context, 0, smsIntent, 0);
builder.addAction(R.drawable.ic_arrow_back, "SMS", pending);
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O)
notificationManagerCompat.notify(i, builder.build());
else
notificationManager.notify(i, builder.build());
}
NotificationCompat.Builder summaryBuilder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_notification)
.setContentTitle("Today Birthdays")
.setContentText(hasBirthday.size() + " new messages")
.setStyle(summaryStyle)
.setGroup(GROUP_KEY)
.setGroupSummary(true)
.setNumber(5);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O)
notificationManagerCompat.notify(SUMMARY_ID, summaryBuilder.build());
else
notificationManager.notify(SUMMARY_ID, summaryBuilder.build());
}
}
Edit : tried to use the setColor on NotificationCompat.Builder builder but it changes the color of the icon. Still don't have any badge.

Thanks to Bob and his link : https://support.google.com/pixelphone/thread/1575301?hl=en,
I found out I had to go to settings < apps and notifications < special app access < notifications < notification access < turn on for "pixel launcher". Then the notification dots would appear as expected !
Well time to write my report I guess.

Related

Alarm creation at this instant android studio

When battery percentage reaches 100, I want to ring an alarm. How can I solve that?
Here is my code:
#Override
public void onReceive(Context context, Intent intent) {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int percentage = level*100/scale;
TextView t = ((MainActivity)context).findViewById(R.id.textView);
t.setText(Integer.toString(percentage)+"%");
if (percentage==100)
//ring alarm
}
}
Prerequisite: Copy the .mp3 sound that you want to play to res/raw
[Create the "raw" directory if necessary]
Here is the commented source which was taken from the latest Android examples and modified to play the custom sound:
private final static int NOTIFICATION_ID = 128;
private final static String CHANNEL_ID = "com.elletlar.stackoverflow.notification_test";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_java);
Notification notification = createNotification();
// Issue the notification.
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(NOTIFICATION_ID, notification);
}
private Notification createNotification() {
createNotificationChannel();
final Uri soundUri = Uri.parse("android.resource://com.elletlar.stackoverflow/" + R.raw.sound);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("Title")
.setContentText("The content")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setSound(soundUri);
return builder.build();
}
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);
final Uri soundUri = Uri.parse("android.resource://com.elletlar.stackoverflow/" + R.raw.sound);
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
channel.setSound(soundUri, audioAttributes);
// 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);
}
}
A Couple of notes:
Many of the Notification examples on StackOverflow no longer work due to Google adding the NotificationChannel concept from Android O
From Android O the sound must be set on the Notification Channel, previously it was set on the Notification itself
If you don't have a sound available, just use: Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); instead

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

How to set NotificationChannel importance to urgent by program?

I want to implement chat notification() like whatsapp (Whatsapp don't know how but reset the Group Message channel importance (Android O) to Urgent).
All going good only i am not able to set NotificationChannel importance to Urgent programmatically.
Here is my work for the Notifications.
NotificationManager mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra(Const.Type.KEY, Const.Type.NOTIFICATION);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, "alert_001")
.setSmallIcon(R.drawable.ic_stat_s)
.setWhen(System.currentTimeMillis())
.setContentTitle("Booking Request")
.setContentText(content)
.setPriority(Notification.PRIORITY_MAX)
.setContentIntent(pendingIntent)
.setOngoing(false)
.setAutoCancel(true);
if (mNotificationManager != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(Const.Channel.Id.ALERT_001,
Const.Channel.Name.BOOKING_ALERT,
NotificationManager.IMPORTANCE_HIGH);
/* Here is no constant like NotificationManager.IMPORTANCE_URGENT
* and i can't even put the another integer value, It not obeying the rules*/
mNotificationManager.createNotificationChannel(channel);
mBuilder.setChannelId(channel.getId());
}
mNotificationManager.notify(1, mBuilder.build());
}
While i am changing the, JSON response for notification like below,
{
priority=high,
message=msgmsg,
source_lat=22.751552,
source_lng=75.895745,
user_detail={},
}
At least it is working like NotificationManager.IMPORTANCE_HIGH, But not like URGENT.
I don't know how whatsapp implemented that can override the URGENT importance even if user changes it manually.
There is a hack:
private String ensureChannelAudibility(String channelMainId, String channelName, Uri soundUri) {
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(App.instance);
List<NotificationChannel> channels = notificationManager.getNotificationChannels();
NotificationChannel existingChanel = null;
int count = 0;
for (NotificationChannel channel : channels) {
String fullId = channel.getId();
if (fullId.contains(channelMainId)) {
existingChanel = channel;
String[] numbers = extractRegexMatches(fullId, "\\d+");
if (numbers.length > 0) {
count = Integer.valueOf(numbers[0]);
}
break;
}
}
if (existingChanel != null) {
if (existingChanel.getImportance() < NotificationManager.IMPORTANCE_DEFAULT) {
notificationManager.deleteNotificationChannel(existingChanel.getId());
existingChanel = null;
}
}
if (existingChanel == null) {
String newId = channelMainId+'_'+(count+1);
NotificationChannel notificationChannel = new NotificationChannel(newId, channelName, NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(notificationChannel);
return newId;
} else {
return existingChanel.getId();
}
}
//Show the notification with channel id returned by the method above
public String[] extractRegexMatches(String source, String regex) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(source);
ArrayList<String> matches = new ArrayList<>();
while (matcher.find()) {
matches.add(matcher.group());
}
String[] result = new String[matches.size()];
matches.toArray(result);
return result;
}
Normally you can only set channel importance when creating it. Once the user changes it, you can not change it back programmatically. The code above tricks the system. It detects if channels importance is lower than needed and if it is, it deletes it and creates another one with a different id. Thus the system things that it's a different channel needed for something else.
So let's say you have a channel with "channelMainId" = wolf. A (wolf_1) channel will be created. Once the user changes it's settings, next channel will be (wolf_2), then
wolf_3, wolf_4 ... wolf_xxxxxxxxxxxx.
Please try this:
String channelId = "YOUR_CHANNEL_ID";
String channelName = "YOUR_CHANNEL_NAME";
int importance = NotificationManager.IMPORTANCE_HIGH;
final NotificationCompat.Builder noBuilder = new NotificationCompat.Builder(
this,channelId)
.setContentTitle("APP_NAME")
.setSmallIcon(//set any Icon)
.setContentText("TEXT")
.setAutoCancel(true);
final NotificationManager notificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
// for oreo-notification
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(
channelId, channelName, importance);
notificationManager.createNotificationChannel(mChannel);
}
Thanks

Notifications not working on Api 27(8.1.0)

Notifications are working for Oreo 8.0(Api 26) and below perfectly fine but they are not working with Oreo 8.1.0.
below is the stack trace of an error
android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=null pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x40 color=0x00000000 actions=2 vis=PRIVATE)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1768)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
I am creating Notification channel for Oreo still it's not working for Oreo 8.1.0. I also refer other stack overflow link but not getting any clue why this error occuring in my case.
UpdateAlarmActivity.java
public class UpcomingAlarmReceiver extends BroadcastReceiver {
public static final String TAG = "UpcomingAlarmReceiver";
public static final String ACTION_DISMISS_NOW = "com.funswitch.funrooster.action.DISMISS_NOW";
public static final String ACTION_CANCEL_NOTIFICATION = "com.funswitch.funrooster.action.CANCEL_NOTIFICATION";
public static final String ACTION_SHOW_SNOOZING = "com.funswitch.funrooster.action.SHOW_SNOOZING";
public static final String EXTRA_ALARM = "com.funswitch.funrooster.extra.ALARM";
public static final String CHANNEL_NAME = "CHANNEL_NOTIFICATION";
String NOTIFICATION_CHANNEL_ID = "io.funswitch.funrooster.Channel";
#Override
public void onReceive(final Context context, final Intent intent) {
final byte[] alarmBytes = intent.getByteArrayExtra(EXTRA_ALARM);
// Un-marshall the bytes into a parcel and create our Alarm with it.
final Alarm alarm = ParcelableUtil.unmarshall(alarmBytes, Alarm.CREATOR);
if (alarm == null) {
throw new IllegalStateException("No alarm received");
}
final long id = alarm.getId();
final NotificationManager nm = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
final boolean actionShowSnoozing = ACTION_SHOW_SNOOZING.equals(intent.getAction());
if (intent.getAction() == null || actionShowSnoozing) {
// Prepare notification
// http://stackoverflow.com/a/15803726/5055032
// Notifications aren't updated on the UI thread, so we could have
// done this in the background. However, no lengthy operations are
// done here, so doing so is a premature optimization.
String title;
String text;
if (actionShowSnoozing) {
if (!alarm.isSnoozed()) {
throw new IllegalStateException("Can't show snoozing notif. if alarm not snoozed!");
}
title = alarm.getLabel().isEmpty() ? context.getString(R.string.alarm) : alarm.getLabel();
text = context.getString(R.string.title_snoozing_until,
formatTime(context, alarm.snoozingUntil()));
} else {
// No intent action required for default behavior
title = context.getString(R.string.upcoming_alarm);
text = formatTime(context, alarm.ringsAt());
}
Intent dismissIntent = new Intent(context, UpcomingAlarmReceiver.class)
.setAction(ACTION_DISMISS_NOW)
.putExtra(EXTRA_ALARM, ParcelableUtil.marshall(alarm));
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
PendingIntent piDismiss = PendingIntent.getBroadcast(context, (int) id,
dismissIntent, PendingIntent.FLAG_CANCEL_CURRENT);
mBuilder
.setSmallIcon(R.drawable.ic_alarm_24dp)
.setContentTitle(title)
.setContentText(text)
.addAction(R.drawable.ic_dismiss_alarm_24dp,
context.getString(R.string.dismiss_now), piDismiss);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, CHANNEL_NAME, importance);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setSound(null, null);
notificationChannel.setShowBadge(false);
notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
assert nm != null;
mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
nm.createNotificationChannel(notificationChannel);
}
Objects.requireNonNull(nm).notify(TAG, (int) id, mBuilder.build());
} else if (ACTION_CANCEL_NOTIFICATION.equals(intent.getAction())) {
Objects.requireNonNull(nm).cancel(TAG, (int) id);
} else if (ACTION_DISMISS_NOW.equals(intent.getAction())) {
new AlarmController(context, null).cancelAlarm(alarm, false, true);
}
}
}
Above is my Java class where I am implementing the code for Notifications. Please help me out or give me some suggestions how can I resolve this error.
In api level 27 google changed the notification methods now in api 27 or upper level you need to create notification channel to send notification.
Channel is categories all types of notifications learn more about notification channel
check this for notification channel
**if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
String id = "id_product";
// The user-visible name of the channel.
CharSequence name = "Product";
// The user-visible description of the channel.
String description = "Notifications regarding our products";
int importance = NotificationManager.IMPORTANCE_MAX;
NotificationChannel mChannel = new NotificationChannel(id, name, importance);
// Configure the notification channel.
mChannel.setDescription(description);
mChannel.enableLights(true);
// Sets the notification light color for notifications posted to this
// channel, if the device supports this feature.
mChannel.setLightColor(Color.RED);
notificationManager.createNotificationChannel(mChannel);
}**
Change your NotificationCompat.Builder constructor:
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
adding the channel id:
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID)

Notification Content Title and Content Text are not shwoing

I am generating local notification with multiple lines. All lines are showing properly but contentTitle and contentText are not showing.
Here is my code to generate a notification:
Intent notificationIntent = new Intent(context, MainActivity.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(notificationIntent);
int num = (int) System.currentTimeMillis();
PendingIntent pendingIntent = stackBuilder.getPendingIntent(num, PendingIntent.FLAG_UPDATE_CURRENT);
String id = "notification_channel_id";
CharSequence name = "Message_Notification";
Bitmap bm = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, id)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("title")
.setContentText("time")
.setAutoCancel(true)
.setGroupSummary(true)
.setGroup(GROUP_KEY)
.setContentIntent(pendingIntent)
.setChannelId(id);
if (subTitle != null) {
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
inboxStyle.setBigContentTitle("Dose Reminder");
if (subTitle.contains("---")) {
String[] splitStrings = subTitle.split("---");
for (int i = 0; i < splitStrings.length; i++) {
inboxStyle.addLine(splitStrings[i]);
}
} else {
inboxStyle.addLine(subTitle);
// Moves the expanded layout object into the notification object.
notificationBuilder.setStyle(inboxStyle);
}
// Moves the expanded layout object into the notification object.
notificationBuilder.setStyle(inboxStyle);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
notificationBuilder.setColor(ContextCompat.getColor(context, R.color.colorAccent));
} else {
notificationBuilder.setLargeIcon(bm);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
// The user.-visible description of the channel.
String description = "Notifications contains messages which was sent by dev team.";
int importance = NotificationManager.IMPORTANCE_MAX;
NotificationChannel mChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_DEFAULT);
// Configure the notification channel.
mChannel.setDescription(description);
mChannel.enableLights(true);
// Sets the notification light color for notifications posted to this
// channel, if the device supports this feature.
mChannel.setLightColor(Color.RED);
if (notificationManager != null) {
notificationManager.createNotificationChannel(mChannel);
}
}
// Sets an ID for the notification
// Gets an instance of the NotificationManager service
final NotificationManager mNotifyMgr =
(NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
// Builds the notification and issues it.
if (mNotifyMgr != null) {
mNotifyMgr.notify(num, notificationBuilder.build());
}
When notification comes "title" and "time" are not showing. It showing "Dose Reminder" and subTitles in multiple lines.
Am I missing something?
setBigContentTitle(CharSequence title)
Overrides ContentTitle in the big form of the template.
https://developer.android.com/reference/android/app/Notification.InboxStyle
Check Use MessagingStyle section
https://developer.android.com/training/notify-user/build-notification
JFYI by default timestamp is gone in push notifications, Android 7 (Nougat) onwards

Categories

Resources