I've been struggling with the new NotificationChannels which is introduced in API 26 and up.
I'm developing an app with an option to choose whether to be notified in four cases:
Sound and Vibrate.
Sound only.
Vibrate only.
No sound or vibrate, just a pop-up.
In all cases, my app notify with sound and vibrate whatever I choose.
My code is:
NotificationCompat.Builder builder;
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder = new NotificationCompat.Builder(context, CHANNEL_ID);
int importance;
NotificationChannel channel;
//Boolean for choosing Sound
if(sound) {
importance = NotificationManager.IMPORTANCE_DEFAULT;
} else {
importance = NotificationManager.IMPORTANCE_LOW;
}
channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, importance);
channel.setDescription(CHANNEL_DESC);
//Boolean for choosing Vibrate
if(vibrate) {
channel.enableVibration(true);
} else {
channel.enableVibration(false);
}
notificationManager.createNotificationChannel(channel);
} else {
builder = new NotificationCompat.Builder(context);
}
if(sound && vibrate) {
//Sound and Vibrate
builder.setDefaults(Notification.DEFAULT_ALL);
} else if(sound && !vibrate) {
//Sound
builder.setDefaults(Notification.DEFAULT_SOUND);
} else if(!sound && vibrate) {
//Vibrate
builder.setDefaults(Notification.DEFAULT_VIBRATE);
} else if(!sound && !vibrate) {
//None
//Do nothing! just notification with no sound or vibration
}
builder.setSmallIcon(R.drawable.ic_logo)
.setContentTitle(title)
.setContentText(text)
.setAutoCancel(true)
.setOnlyAlertOnce(false)
.setPriority(Notification.PRIORITY_MAX);
Also, I change CHANNEL_ID every time I run the app, so it gets a fresh Channel ID every time just for testing until I find a solution.
Of course, it works fine with API less than 26.
Thank you, guys!
Thank you all guys,
I managed to solve it by simply creating a NotificationCompat.Builder and NotificationChannel for each and every case, and notify each Builder when its condition is met.
I don't know if this is the best practice, but I'll try to optimize the code later, if anyone has an opinion on that feel free. But it worked so fine now.
Here's my code:
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationCompat.Builder builder_all, builder_sound, builder_vibrate, builder_none;
NotificationChannel channel_all = new NotificationChannel(CHANNEL_ID_ALL, CHANNEL_NAME_ALL, NotificationManager.IMPORTANCE_HIGH);
channel_all.enableVibration(true);
notificationManager.createNotificationChannel(channel_all);
NotificationChannel channel_sound = new NotificationChannel(CHANNEL_ID_SOUND, CHANNEL_NAME_SOUND, NotificationManager.IMPORTANCE_HIGH);
channel_sound.enableVibration(false);
notificationManager.createNotificationChannel(channel_sound);
NotificationChannel channel_vibrate = new NotificationChannel(CHANNEL_ID_VIBRATE, CHANNEL_NAME_VIBRATE, NotificationManager.IMPORTANCE_HIGH);
channel_vibrate.setSound(null, null);
channel_vibrate.enableVibration(true);
notificationManager.createNotificationChannel(channel_vibrate);
NotificationChannel channel_none = new NotificationChannel(CHANNEL_ID_NONE, CHANNEL_NAME_NONE, NotificationManager.IMPORTANCE_HIGH);
channel_none.setSound(null, null);
channel_none.enableVibration(false);
notificationManager.createNotificationChannel(channel_none);
//Boolean for Sound or Vibrate are chosen
if(sound && vibrate) {
builder_all = new NotificationCompat.Builder(context, CHANNEL_ID_ALL);
builder_all.setSmallIcon(R.drawable.ic_logo)
.setContentTitle(title)
.setContentText(text)
.setAutoCancel(true)
.setOnlyAlertOnce(false);
switch (transition) {
case Geofence.GEOFENCE_TRANSITION_ENTER:
builder_all.setSmallIcon(R.drawable.ic_entered_white);
break;
case Geofence.GEOFENCE_TRANSITION_EXIT:
builder_all.setSmallIcon(R.drawable.ic_left_white);
break;
}
notificationManager.notify(notificationID, builder_all.build());
} else if(sound && !vibrate) {
builder_sound = new NotificationCompat.Builder(context, CHANNEL_ID_SOUND);
builder_sound.setSmallIcon(R.drawable.ic_logo)
.setContentTitle(title)
.setContentText(text)
.setAutoCancel(true)
.setOnlyAlertOnce(false);
switch (transition) {
case Geofence.GEOFENCE_TRANSITION_ENTER:
builder_sound.setSmallIcon(R.drawable.ic_entered_white);
break;
case Geofence.GEOFENCE_TRANSITION_EXIT:
builder_sound.setSmallIcon(R.drawable.ic_left_white);
break;
}
notificationManager.notify(notificationID, builder_sound.build());
} else if(!sound && vibrate) {
builder_vibrate = new NotificationCompat.Builder(context, CHANNEL_ID_VIBRATE);
builder_vibrate.setSmallIcon(R.drawable.ic_logo)
.setContentTitle(title)
.setContentText(text)
.setAutoCancel(true)
.setOnlyAlertOnce(false);
switch (transition) {
case Geofence.GEOFENCE_TRANSITION_ENTER:
builder_vibrate.setSmallIcon(R.drawable.ic_entered_white);
break;
case Geofence.GEOFENCE_TRANSITION_EXIT:
builder_vibrate.setSmallIcon(R.drawable.ic_left_white);
break;
}
notificationManager.notify(notificationID, builder_vibrate.build());
} else if(!sound && !vibrate) {
builder_none = new NotificationCompat.Builder(context, CHANNEL_ID_NONE);
builder_none.setSmallIcon(R.drawable.ic_logo)
.setContentTitle(title)
.setContentText(text)
.setAutoCancel(true)
.setOnlyAlertOnce(false);
switch (transition) {
case Geofence.GEOFENCE_TRANSITION_ENTER:
builder_none.setSmallIcon(R.drawable.ic_entered_white);
break;
case Geofence.GEOFENCE_TRANSITION_EXIT:
builder_none.setSmallIcon(R.drawable.ic_left_white);
break;
}
notificationManager.notify(notificationID, builder_none.build());
}
} else {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
if(sound && vibrate) {
//Sound and Vibrate
builder.setDefaults(Notification.DEFAULT_ALL);
} else if(sound && !vibrate) {
//Sound
builder.setDefaults(Notification.DEFAULT_SOUND);
} else if(!sound && vibrate) {
//Vibrate
builder.setDefaults(Notification.DEFAULT_VIBRATE);
} else if(!sound && !vibrate) {
//None
//Do nothing! just notification with no sound or vibration
}
builder.setSmallIcon(R.drawable.ic_logo)
.setContentTitle(title)
.setContentText(text)
.setAutoCancel(true)
.setOnlyAlertOnce(false)
.setPriority(Notification.PRIORITY_MAX);
switch (transition) {
case Geofence.GEOFENCE_TRANSITION_ENTER:
builder.setSmallIcon(R.drawable.ic_entered_white);
break;
case Geofence.GEOFENCE_TRANSITION_EXIT:
builder.setSmallIcon(R.drawable.ic_left_white);
break;
}
notificationManager.notify(notificationID, builder.build());
}
i found this in the documentation. May be it will help you :
On Android 8.0 (API level 26) and above, importance of a notification is determined by the importance of the channel the notification was posted to. Users can change the importance of a notification channel in the system settings (figure 12). On Android 7.1 (API level 25) and below, importance of each notification is determined by the notification's priority.
And also :
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.
And finally :
Individual notifications must now be put in a specific channel.
Users can now turn off notifications per channel, instead of turning off all notifications from an app.
Apps with active notifications display a notification "badge" on top of their app icon on the home/launcher screen.
Users can now snooze a notification from the drawer. You can set an automatic timeout for a notification.
Some APIs regarding notification behaviors were moved from Notification to NotificationChannel. For example, use NotificationChannel.setImportance() instead of NotificationCompat.Builder.setPriority() for Android 8.0 and higher.
If your sound and vibrate bools come from your app settings, then note that the intention is you should remove those from your app and send the user to the channel settings instead:
"After you create a notification channel, you cannot change the notification channel's visual and auditory behaviors programmatically—only the user can change the channel behaviors from the system settings. To provide your users easy access to these notification settings, you should add an item in your app's settings UI that opens these system settings."
https://developer.android.com/training/notify-user/channels#UpdateChannel
Related
Foreground service notification shows too slowly on Android 12. Used ContextCompat.startForegroundService(...) and mContext.startForegroundService(...). It still shows in 5-10 seconds.
Here is an example of my code:
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "Counting steps", NotificationManager.IMPORTANCE_DEFAULT);
channel.enableVibration(false);
channel.setSound(null, null);
channel.setShowBadge(false);
notificationManager.createNotificationChannel(channel);
}
}
The onStartCommand method:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String input = intent.getStringExtra("numberOfSteps");
createNotificationChannel();
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
Notification.Builder notificationBuilder = new Notification.Builder(this, CHANNEL_ID)
.setContentTitle("Counting steps")
.setContentText(input)
.setSmallIcon(R.drawable.ic_baseline_directions_walk_24)
.setContentIntent(pendingIntent);
startForeground(FOREGROUND_ID, notificationBuilder.build());
}
return START_STICKY;
}
How can I start or show a foreground service notification quickly?
Services that show a notification immediately
If a foreground service has at least one of the following
characteristics, the system shows the associated notification
immediately after the service starts, even on devices that run Android
12 or higher:
The service is associated with a notification that includes action
buttons. The service has a foregroundServiceType of
mediaPlayback, mediaProjection, or phoneCall. The service
provides a use case related to phone calls, navigation, or media
playback, as defined in the notification's category
attribute. The service has opted out of the behavior
change by passing FOREGROUND_SERVICE_IMMEDIATE into
setForegroundServiceBehavior() when setting up the
notification.
On Android 13 (API level 33) or higher, if the user denies the
notification permission, they still see notices related to foreground
services in the Foreground Services (FGS) Task Manager but don't see
them in the notification drawer.
See: Services that show a notification immediately
Java example code:
Notification.Builder notificationBuilder = new Notification.Builder(this, CHANNEL_ID)
.setContentTitle("Counting steps")
.setContentText(message)
.setSmallIcon(R.drawable.your_cool_icon)
.setContentIntent(pendingIntent);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
notificationBuilder.setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE);
}
Kotlin example:
val notificationBuilder: Notification.Builder =
Notification.Builder(this, CHANNEL_ID)
.setContentTitle("Notification title")
.setContentText("Content title")
.setSmallIcon(R.drawable.your_cool_icon)
.setContentIntent(pendingIntent)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
notificationBuilder.setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE)
}
I am trying to create notifications in android but no matter what importance and priority I set, there's no sound. I am assuming sound (ringtone) is handle by android itself I don't need to provide any mp3/wav file. I am trying on android 8.1 (actual device), 8.0 (emulator) and 8.1 (emulator). Notification channel created on actual device has sound off by default, I don't know why and on emulator sound is on but still no sound played on notification
Here is my code:
public void sendMessage(View view) {
createNotificationChannel();
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("New Notification")
.setContentText("Lorem Ipsum")
.setPriority(NotificationCompat.PRIORITY_HIGH);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(1, 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 = "basic-channel";
String description = "Lorem Ipsum";
int importance = NotificationManager.IMPORTANCE_HIGH;
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);
}
}
Channel on Actual Device
Channel on Emulator
Root Cause:
For actual device, that's OEM's problem, which in my case is Xiaomi and I found this link threema.ch/en/faq/notification_channels_xiaomi which says that xiaomi sets sound=off for all app except select few like FB, whatsApp, etc.
For emulator, we need to complete the setup process after which notification starts making sound.
When you build the notification, you need to indicate that you want to use the default system values:
builder.setDefaults(Notification.DEFAULT_ALL)
And remember to clear the app data or reinstall the app to properly recreate the notification channel. A notification channel will retain its initial configuration even if you recreate it in code.
Check this out :
//Define sound URI
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("New Notification")
.setContentText("Lorem Ipsum")
.setPriority(NotificationCompat.PRIORITY_HIGH);
.setSound(soundUri); //This sets the sound to play
I'm using a foreground service with notifications. It it's important that my notification pops up by itself and not just when you drag down the top bar.
It's working most of the time. Except on Xiaomi phones. And weirdly enough it just stopped working on a Pixel 2 API 29 as well...
I know they don't show up on older APIs if there is no sound OR vibration. Maybe it has something to do with that.
StatusNotification statusNotification = new StatusNotification(getApplicationContext());
startForeground(1, statusNotification.notification());
...
public class StatusNotification {
Context context;
long[] shortVibration;
StatusNotification(Context context){
this.context = context;
shortVibration = new long[] {0L, 100L, 0L};
// just {100L} doesn't vibrate at all
// but it has to be one short vibration and not the default one
// VibrationEffect.createOneShot() is only for Oreo and higher
createNotificationChannel();
}
void createNotificationChannel(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager manager = context.getSystemService(NotificationManager.class);
NotificationChannel channel2 = new NotificationChannel("channel2", "Channel 2", NotificationManager.IMPORTANCE_HIGH);
channel2.setDescription("Channel 2");
channel2.enableVibration(true);
channel2.setSound(null, null);
channel2.setVibrationPattern(shortVibration);
manager.createNotificationChannel(channel2);
}
}
Notification notification(){
return new NotificationCompat.Builder(context, "channel2")
.setProgress(100,100, false)
.setContentTitle("Title")
.setColor(context.getResources().getColor(R.color.colorPrimary))
.setSmallIcon(R.drawable.ic)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setVibrate(shortVibration)
.build();
}
}
Use case is I have to send logout request to server when app get killed from recent lists. I use onTaskRemoved to handle that however in Android O and P I get notification bar saying "app is running" that I want to avoid. Here is how I run foreground service:
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
channelId = "my_service_channel_id";
String channelName = "My Foreground Service";
NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_LOW);
channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
channel.setSound(null, null);
notificationManager.createNotificationChannel(channel);
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this, channelId)
.setContentTitle("")
.setAutoCancel(true)
.setContentText("");
startForeground(NOTIFY_ID, builder.build());
//notificationManager.cancel(NOTIFY_ID); // It doesn't remove notification
//notificationManager.deleteNotificationChannel(channelId); // it causes crash
}
I already tried JobScheduler but onTaskRemoved doesn't get trigger. Any helps would be appreciated.
My application could play some audio.
Once user press at the audio title the notification with the play/pause/rewind buttons appears at the notification drawer.
I noticed that in Android O (8) this notification appears with "heads-up" effect.
I don't need heads-up notification, I need just silent common notification. How can I disable "heads-up" effect?
NotificationCompat.Builder notificationBuilder;
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationBuilder = new NotificationCompat.Builder(getApplicationContext(), Constants.CHANNEL_ID);
} else {
notificationBuilder = new NotificationCompat.Builder(getApplicationContext());
}
Notification notification = notificationBuilder
.setSmallIcon(R.drawable.tray_icon)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setWhen(System.currentTimeMillis())
.setContent(remoteViews)
.setChannelId(Constants.CHANNEL_ID)
.build();
notification.defaults = 0;