I am working with AlarmManager, and when the alarm starts it also shows notifications. I have created notifications for Oreo and for before Oreo. Notifications before Oreo work properly - I can disable sounds and set lights, but I cannot make this work in Oreo. I had the similar issue with vibrations, but was able to find a working solution. I have tried A LOT of things (1, 2, 3, 4, 5, 6...), from NotificationCompat, to changing importance, but was unable to make it work.
My issue is only with Oreo notifications, I cannot disable sound (it goes of every time), and I cannot make light blink. I have went through a bunch of SO questions, and official documentation. Some solutions are obsolete, deprecated (NotificationCompat.Builder), others do not work at all (including some examples from the official documentation).
Here is my code for both Oreo (not working) and for older (working):
//region Oreo notifications
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "AlarmNotification";
String description = "Alarm notification";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel mChannel = new NotificationChannel(channelIdOreo, name, importance);
mChannel.setDescription(description);
mChannel.setShowBadge(true);
mChannel.enableLights(true);
mChannel.setLightColor(Color.RED);
if (notificationManager != null) {
notificationManager.createNotificationChannel(mChannel);
}
Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
if (sNotifications.equals("false")) {
//NOT WORKING
mChannel.setSound(null, null);
}
//VIBRATION WORKING
if (sVibration.equals("true")) {
if (vibrator != null && vibrator.hasVibrator()) {
VibrationEffect effect = VibrationEffect.createOneShot(1000, VibrationEffect.DEFAULT_AMPLITUDE);
vibrator.vibrate(effect);
}
}
Notification notification = new Notification.Builder(context, channelIdOreo)
.setContentTitle(contentTitleText)
.setContentText(contentContentText)
.setNumber(1)
.setSmallIcon(whiteLogo)
.setBadgeIconType(whiteLogo)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.build();
if (notificationManager != null) {
notificationManager.notify(notificationCode, notification);
}
}
//endregion
//region Pre-Oreo notifications
else {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, channelId)
.setSmallIcon(whiteLogo)
.setLargeIcon(largeIcon)
.setContentTitle(contentTitleText)
.setContentText(contentContentText)
.setOngoing(false)
.setNumber(1)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setAutoCancel(true);
mBuilder.setLights(colorPPDOrange, 1000, 2000);
if (sNotifications.equals("true")) {
mBuilder.setSound(uri);
}
if (sVibration.equals("true")) {
mBuilder.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
}
mBuilder.setContentIntent(pendingIntent);
if (notificationManager != null) {
notificationManager.notify(notificationCode, mBuilder.build());
}
}
//endregion
Finally found an answer. Every time I change anything related to my channel I had to have my channel id changed to a completely new id, that was NEVER used before. It cannot just be different from the current id. Other than this I replaced my string resource with actual string in code. Also I had to move a few lines of code as shown below.
This is how my code looks like now:
String channelIdOreo = "FfffffF";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//region Oreo otification
Notification notification = new Notification.Builder(context, channelIdOreo)
.setContentTitle(contentTitleText)
.setContentText(contentContentText)
.setNumber(1)
.setSmallIcon(whiteLogo)
.setBadgeIconType(whiteLogo)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.build();
//endregion
NotificationChannel mChannel = new NotificationChannel(channelIdOreo, "Channel human readable title and stuff", NotificationManager.IMPORTANCE_DEFAULT);
mChannel.enableLights(true);
mChannel.setLightColor(Color.YELLOW);
//region Conditions from settings
if (sNotifications.equals("true")) {
mChannel.setSound(uri, null);
} else {
mChannel.setSound(null, null);
}
if (sVibration.equals("true")) {
mChannel.setVibrationPattern(new long[]{1000, 1000, 1000, 1000, 1000});
} else {
mChannel.enableVibration(false);
}
//endregion
if (notificationManager != null) {
notificationManager.createNotificationChannel(mChannel);
}
if (notificationManager != null) {
notificationManager.notify(notificationCode, notification);
}
}
Hope this will save some time to someone.
Related
I'm trying to create an app with 3 different notification sounds (But not different notification channels), I create custom notification sound, but when I try to change the sound, it stays still the same, I also tried to delete the channel and create it again but notification sound does not change.
First I create Channel:
String CHANNEL_ID = Constants.notification_channel_ID;
int NOTIFICATION_ID = 1991;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager mNotificationManager = getSystemService(NotificationManager.class);
NotificationChannel existingChannel = mNotificationManager.getNotificationChannel(CHANNEL_ID);
if (existingChannel != null){
mNotificationManager.deleteNotificationChannel(CHANNEL_ID);
}
CharSequence name = getResources().getString(R.string.drink_reminder);
String description = getResources().getString(R.string.notification_to_remind_you_to_drink);
int importance = NotificationManager.IMPORTANCE_HIGH;
if (s1 = true){
Uri sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.test_sound);
}else{
Uri sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.test_sound1);
}
AudioAttributes audioAttributes = new AudioAttributes.Builder().setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION ).setUsage(AudioAttributes.USAGE_NOTIFICATION).build() ;
NotificationChannel notificationChannel = new NotificationChannel( CHANNEL_ID , name , importance) ;
notificationChannel.setDescription(description);
notificationChannel.enableLights(true) ;
notificationChannel.setLightColor(Color.BLUE) ;
notificationChannel.enableVibration( tinyDB.getBoolean(Constants.settings_notification_vibration_key,true));
notificationChannel.setVibrationPattern( new long []{ 100 , 200 , 300 , 400 , 500 , 400 , 300 , 200 , 400 }) ;
notificationChannel.setSound(sound , audioAttributes) ;
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(notificationChannel);
}
Then I create Notifiaction:
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(this.getResources().getString(R.string.app_name))
.setContentText(this.getResources().getString(R.string.text))
.setContentIntent(pendingIntent)
.setSound(sound)
.setChannelId(CHANNEL_ID)
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(NOTIFICATION_ID, builder.build());
So on first time this code works, when later on I call this method again to and change the sound, notifications are still working with same sound like in beginning, also I can't disable, enable vibration (It stays the same like first time is configured). As you see I'm also trying to recreate notification channel, but still the same.
Any help will be appriciated.
Resolved by setting up a silent notification and adding manual sound and vibration.
So on When I create Channel I use:
notificationChannel.enableVibration(false);
notificationChannel.setSound(null,null);
Also when I build notification I add this code:
.setSilent(true)
Than to vibrate I use this:
private void vibrate (Context context){
Vibrator v = (Vibrator) context.getSystemService(VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
v.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE));
} else {
//deprecated in API 26
v.vibrate(500);
}
}
and for notification ringtone I use this code:
private void playSound(Context context, String SoundUri){
Uri rawPathUri = Uri.parse(SoundUri);
Ringtone r = RingtoneManager.getRingtone(context, rawPathUri);
r.play();
}
When SoundUri is the String that matches the sound from settings user have choosen.
I am sharing two images please have a look on it you will understand my problem
in fist image notification comes successfully as shown better me notification but
I want it to come and show first on main screen as shown in second image just this telegram notification.
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
// r.play();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
r.setLooping(false);
}
// vibration
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
long[] pattern = {100, 300, 300, 300};
v.vibrate(pattern, -1);
int resourceImage = getResources().getIdentifier(remoteMessage.getNotification().getIcon(), "drawable", getPackageName());
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "CHANNEL_ID");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder.setSmallIcon(R.mipmap.betterme);
} else {
builder.setSmallIcon(R.mipmap.betterme);
}
Intent resultIntent = new Intent(this, SplashScreen.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentTitle(remoteMessage.getNotification().getTitle());
builder.setContentText(remoteMessage.getNotification().getBody());
builder.setContentIntent(pendingIntent);
builder.setStyle(new NotificationCompat.BigTextStyle().bigText(remoteMessage.getNotification().getBody()));
builder.setAutoCancel(true);
builder.setOngoing(true);
builder.setPriority(NotificationCompat.PRIORITY_MAX);
builder.setSound(notification);
mNotificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
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);
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
channel.setSound(notification, audioAttributes);
mNotificationManager.createNotificationChannel(channel);
builder.setChannelId(channelId);
}
mNotificationManager.notify(100, builder.build());
}
}
first image
second image
If I understand correctly, you would like to have a heads up notification.
Note, that the android system decides when to make a notification a heads up notification and has the final say - not you the developer. Here you can find some examples when it does so: https://developer.android.com/guide/topics/ui/notifiers/notifications#Heads-up
Make sure that your setup reflects these. From your sample it seems to be the case, but maybe you have changed the notification channel settings (from the app settings), which override your code preferences (the user has precedence over the app).
Additionally, note that if you swipe the heads up notification in a upward direction (not sideways), Android starts a cool off time, where no heads up notifications from that app appears for a few seconds (or more). You can try that with Telegram or any other app as well. After the cool-off time, it starts showing up again like a heads up notification. This is a way Android utilises to prevent apps to be annoying to users.
Seems there is no problem in the notification. But your channel is already created with normal notification and you update to IMPORTANCE_HIGH for NotificationChannel.
Once the channel is created with priority it cannot be changed. So you can either change the channel id or uninstall and reinstall and test it.
I am implementing Notifications in android. I want to change the icon of notification, but the problem is that setSmallIcon is not working. My custom icon is showing in the lollipop device but not showing the custom icon above lollipop devices.
I have tried the following code:
send_notification.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Bitmap icon = BitmapFactory.decodeResource(getResources(),R.drawable.book2);
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this)
.setContentTitle("New Book Added")
.setContentText("Android with java")
.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(icon)
.bigLargeIcon(null));
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder.setSmallIcon(R.drawable.ic_notification);
} else {
builder.setSmallIcon(R.drawable.notification);
}
NotificationManager manager= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(1,builder.build());
}
}
The big picture is also not showing. Please Help.
EDIT:
Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.test);
String channelId = getString(R.string.default_notification_channel_id);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId);
if (remoteMessage.getData().size() > 0) {
String title = remoteMessage.getData().get("title");
String text = remoteMessage.getData().get("body");
builder.setContentTitle(title)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText(text)
.setLargeIcon(icon)
.setPriority(Notification.PRIORITY_MAX)
.setStyle(new NotificationCompat.BigPictureStyle()
.bigLargeIcon(icon));
} else if (remoteMessage.getNotification() != null) {
String title = remoteMessage.getNotification().getTitle();
String text = remoteMessage.getNotification().getBody();
builder.setContentTitle(title)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText(text)
.setLargeIcon(icon)
.setPriority(Notification.PRIORITY_MAX)
.setStyle(new NotificationCompat.BigPictureStyle()
.bigLargeIcon(icon));
}
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(channelId, "Testing channel", NotificationManager.IMPORTANCE_DEFAULT);
manager.createNotificationChannel(notificationChannel);
}
manager.notify(1, builder.build());
Try uninstalling and reinstalling the 100% fresh App. Android keeps cache so things work more quickly and the notification is one of those things.
Uninstalling and reinstalling worked for my issue some time ago.
Also do remember that in Android Oreo and above, in order for notifications to work; notification channels must be created and also the notification that you're creating should be assigned to one of them.
EDIT
What I've tried (and it works for me): (Sample in Kotlin but should be similar enough);
fun onClick(view: View) {
var icon_resource = R.drawable.ic_mtrl_chip_close_circle
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
icon_resource = R.drawable.ic_mtrl_chip_checked_circle
}
val icon = BitmapFactory.decodeResource(resources,R.mipmap.ic_launcher_round)
val notification = NotificationCompat.Builder(this)
.setSmallIcon(icon_resource)
.setContentTitle("New Book Added")
.setContentText("Android with java")
.setLargeIcon(icon)
.setStyle(NotificationCompat.BigPictureStyle()
.bigPicture(icon)
.bigLargeIcon(null)).build()
val manager= getSystemService(NOTIFICATION_SERVICE) as NotificationManager
manager.notify(1,notification)
}
SECOND EDIT
I think there's a problem with your image, (as there was in mine; sizes or something). After spending a lot of time trying to figure out why it didn't display the launcher icon in the notifications I decided to try with one of my images that I had laying around...
Tested with Android O; API 28
And here are the results:
Feel free to try with the original image I used:
Here's the code that is powering these results; it's not very different from the first one...
// Parametherise this drawable with an if statement of your own
var icon_resource = R.drawable.ic_mtrl_chip_close_circle
val manager= NotificationManagerCompat.from(this)
// This is required because the testing device is an Android O
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
manager.createNotificationChannel(
NotificationChannel("CUSTOM_NOTIFICATIONS", "StackOverflow", NotificationManager.IMPORTANCE_HIGH)
)
}
val icon = BitmapFactory.decodeResource(resources,R.mipmap.dafuq)
val notification = NotificationCompat.Builder(this, "CUSTOM_NOTIFICATIONS")
.setSmallIcon(icon_resource)
.setContentTitle("New Book Added")
.setContentText("Android with java")
.setLargeIcon(icon)
.setStyle(NotificationCompat.BigPictureStyle()
.bigPicture(icon)
.bigLargeIcon(null)).build()
manager.notify(1,notification)
Additional info:
When I'm using a wrong image, I get this pesky log in my Logcat. Check for the same or similars!
2019-04-10 20:11:02.120 3434-3434/com.example.deletemeapp D/skia: --- Failed to create image decoder with message 'unimplemented'
What you want to do is create the notification icon as follows:
NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this)
.setContentTitle("New Book Added")
.setContentText("Android with java");
Now Add:
NotificationCompat.BigPictureStyle s = new NotificationCompat.BigPictureStyle().bigPicture(bitmap_image);
s.setSummaryText("Summary text appears on expanding the notification");
//Set the style of the notification to this big picture style
builder.setStyle(s);
For the versioning add this:
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
// Marshmallow+
}else{
//below Marshmallow
}
Hope this helps :)
I'm struggling with complex local notifications on Android for a long time now.
I have a list of events. The user is able to choose when he/she would like to be notified:
on the same day of the event
one day before the event starts
two days before the event starts
He/she is also able to set the time when he/she wants to get notified. Every time is possible. He/she is also able to only get notified by different types of events.
What happens is, that it works fine with every device except the Samsung Galaxy Phones. Users told me that they are receiving a notification exactly one time (when they set them up) and then never again.
I tried almost everything, I'm running out of ideas. It looks like Samsung has some issues with notifications but it works for some other apps. So what's the difference between their code and mine.
Maybe someone else knows this issue and can help me out. This would be so amazing!
Here comes my code:
public int setEventNotifications(List<Event> chosenEvents) {
SharedPreferences settings = context.getSharedPreferences(Constants.PREFS_EVENT_SETTINGS, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
ArrayList<PendingIntent> intentArray = new ArrayList<>();
// To cancel an existing pending intent you need to recreate the exact same and cancel it -__-
// So pending intents need to be stored in the database
deleteOldGarbagePendingIntents();
// get notification settings from shared prefs
int hours = 0;
int minutes = 0;
String time = settings.getString(Constants.PREFS_EVENT_TIME, "00:00");
String parts[] = time.split(":");
try {
hours = Integer.parseInt(parts[0]);
minutes = Integer.parseInt(parts[1]);
} catch (Exception e) {
Log.e(TAG, "Invalid time. Cannot be parsed: " + time);
}
String interval = settings.getString(Constants.PREFS_EVENT_INTERVAL, "");
String communeId = settings.getString(Constants.PREFS_EVENT_COMMUNE_ID, "");
String regionId = settings.getString(Constants.PREFS_EVENT_REGION_ID, "");
for (Event event : chosenEvents) {
// check if date is in the future
Intent intent = new Intent(context, AlarmGarbageReceiver.class);
intent.putExtra("request_code", Integer.parseInt(event.getId()));
intent.putExtra("event_type", event.getGarbageType().getType());
intent.putExtra("event_date", event.getPickupDateAsDate().getTime());
// calculate trigger time
long triggerTime = calculateTriggerTime(event.getPickupDateAsDate(), hours, minutes, interval);
Calendar alarmCalendar = Calendar.getInstance();
alarmCalendar.setTimeInMillis(triggerTime);
try {
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, Integer.parseInt(event.getId()), intent, FLAG_UPDATE_CURRENT);
if (alarmManager != null) {
alarmManager.set(AlarmManager.RTC_WAKEUP, alarmCalendar.getTimeInMillis(), pendingIntent);
} else {
Log.e(TAG, "Alarmmanager is null");
}
intentArray.add(pendingIntent);
// save intents in database
dbHelper.insertEventData(event.getId(), event.getEventType().getType(), String.valueOf(event.getPickupDateAsDate().getTime()), event.getLocation(), event.getEventType().getColor(), communeId, regionId);
} catch (SecurityException securityException) {
Log.e(TAG, "Security Exception");
securityException.printStackTrace();
} catch (Exception exception) {
Log.e(TAG, "Exception");
exception.printStackTrace();
}
}
return intentArray.size();
}
AlarmEventReceiver class:
public class AlarmEventReceiver extends BroadcastReceiver {
private static final String NOTIFICATION_CHANNEL_NAME = "xxx_events";
private static final String NOTIFICATION_CHANNEL_ID = "xxx_events_1";
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getExtras() != null) {
Log.e(TAG, AlarmEventReceiver.class.getSimpleName() + " request code: " + intent.getExtras().getInt("request_code"));
}
int eventId = intent.getExtras().getInt("request_code");
String eventType = intent.getExtras().getString("event_type");
long pickupDate = intent.getExtras().getLong("event_date");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(pickupDate);
calendar.set(Calendar.HOUR, 6);
calendar.set(Calendar.MINUTE, 0);
long finalDate = calendar.getTimeInMillis();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder;
Intent resultIntent = new Intent(context, EventCalendarActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(EventCalendarActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
if (notificationManager == null) {
notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
}
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
builder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
if (notificationManager != null) {
notificationManager.createNotificationChannel(notificationChannel);
} else {
Log.e(TAG, "Notification Manager is NULL");
}
if (eventType != null) {
builder.setChannelId(NOTIFICATION_CHANNEL_ID)
.setDefaults(Notification.DEFAULT_ALL)
.setContentTitle("Erinnerung")
.setContentText(eventType)
.setWhen(finalDate)
.setContentIntent(resultPendingIntent)
.setAutoCancel(false)
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
}
} else {
builder = new NotificationCompat.Builder(context);
builder.setContentTitle("Erinnerung")
.setDefaults(Notification.DEFAULT_ALL)
.setContentText(eventType)
.setWhen(finalDate)
.setContentIntent(resultPendingIntent)
.setAutoCancel(false)
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
.setPriority(Notification.PRIORITY_DEFAULT);
}
Notification notification = builder.build();
if (notificationManager != null) {
notificationManager.notify(eventId, notification);
} else {
Log.e(TAG, "notificationManager is NULL");
}
}
}
I once had the chance to run it on a samsung phone and I think I remember there was some kind of SecurityException thrown because the phone was not able to update notifications. There was only a capacity of 500 notifications and if try to update them, old ones won't be deleted, but new ones created. You therefore reach 500 notifications quite fast and that's when the SecurityException is thrown. But I can't find the source for this anymore...
I browsed a related issue in the past, it happened on a Galaxy Note, although I'm not sure it will help.
mNotificationManager.cancel(notificationId);
mNotificationManager.notify(++notificationId, notification);
Each time a new notification has to be created, manually cancel the previous one and also update the notificationID each time.
It is working fine, tested on Samsung Galaxy s7 edge
fun showDownloadNotification() {
try {
// val selectedUri = Uri.parse(Environment.getExternalStorageState())
val notiIntent = Intent(DownloadManager.ACTION_VIEW_DOWNLOADS)
notiIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
// startActivity(intent);
val pendingIntent: PendingIntent = PendingIntent.getActivity(baseActivity, 0, notiIntent, PendingIntent.FLAG_CANCEL_CURRENT)
val builder = NotificationCompat.Builder(baseActivity, "")
.setSmallIcon(notificationIcon)
.setContentTitle("Subject Topic downloaded")
.setContentText(fileName)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
val notificationManager: NotificationManagerCompat = NotificationManagerCompat.from(baseActivity)
// notificationId is a unique int for each notification that you must define
notificationManager.notify(1, builder.build())
} catch (e: Exception) {
// Log.e(FragmentActivity.TAG, "Notification $e")
}
}
Might be helpful !
I also had the similar issue with Samsung devices, This is what I have done:
consider this:
builder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
In the above line we have passed NOTIFICATION_CHANNEL_ID.
Now later in the code this is also added:
builder.setChannelId(NOTIFICATION_CHANNEL_ID) // don't call this method
We have already given the channel id to the builder via constructor we don't need to pass that again. remove builder.setChannelId(NOTIFICATION_CHANNEL_ID). And it will also work on samsung devices.
I have a phone under Android 8 and I begin Android programmation with Android Studio. Some apps like Snapchat or Facebook makes my phone light a led with their custom colors (yellow & blue) when a notification comes.
I want to do the same with my app, I searched a lot and nothing works, the notification appears but not the white light. I checked my phone settings and my app is allowed to light the led.
public class Notification
{
public Notification(String channelId, String channelName, Context context, String title, String body, Intent intent)
{
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
int notificationId = 1;
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 nbuilder = new NotificationCompat.Builder(context, channelId)
.setLights(Color.WHITE, 500, 100) // doesn't work
.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 }) // doesn't work
.setContentTitle(title)
.setContentText(body);
TaskStackBuilder stackBuilder =
TaskStackBuilder.create(context);
stackBuilder.addNextIntent(intent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
nbuilder.setContentIntent(resultPendingIntent);
notificationManager.notify(notificationId, nbuilder.build());
}
}
I tried calling the setLights() and setVibrate() after setContentText() and I tried calling these voids just before the notify() but it didn't changed anything.
I instanciate my class in the onCreate() :
new Notification("channel-01", "MathWellan Notification", this, "Twitter", "Follow me on Twitter !", new Intent(Intent.ACTION_VIEW, Uri.parse("twitter://user?screen_name=MathWellan")));
Sorry for my bad english, I'm french and I hope you can help me !
Thanks by advance :)
Use this line of code to change notification LED color: your_notification.ledARGB = Color.YOUR_COLOR;
Usage example:
NotificationManager notif = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notif.cancel(1); // clear previous notification
final Notification notification = new Notification();
notification.ledARGB = Color.MAGENTA;
notification.ledOnMS = 1000;
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
notif.notify(1, notification);
Note : screen should be locked when you test it , because notification LED will be highlighted only when screen is off. Maybe that's your problem.