Notifications on android oreo - dynamically enable sound/vibration - android

I have a foreground service that shows a progress notification and if it is finished, the notification is reused as a normal notification to show the service's result
I allow the user to define inside my app if the final notification is silent or not. So here is what I do:
// 1) Create notifcation channel in my app, once only
NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, importance);
notificationChannel.enableLights(false);
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
// 2) Init notification
notificationBuilder = new NotificationCompat.Builder(this, notificationChannelId);
notificationBuilder.setAutoCancel(false);
notificationBuilder.setOngoing(true);
notificationBuilder.setTicker(ticker);
notificationBuilder.setContentText(title);
// 3) Updating the notification to show the services progress
notificationBuilder.setContentTitle(title);
notificationBuilder.setContentText(subTitle);
// 4) preparing the final notification
if (!MainApp.getPrefs().silentNotifications()) {
if (globalError || updated > 0 || prepared > 0 || contactsWithError.size() > 0) {
notificationBuilder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE);
notificationBuilder.setVibrate(new long[]{0, 500});
notificationBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
} else {
notificationBuilder.setVibrate(new long[]{});
notificationBuilder.setSound(null);
}
}
Problems
an android oreo user told me, the notification is making a sound/vibrates on each update
the same user told me, after a restart, the sound/vibration is gone
What I want
I want that the notification channel vibrates and plays a sound by default (if the user did not change this in the android settings for my channel)
I want to dynamically decide that I don't play sounds/vibrate even if sound/vibration is enabled
If the user disables sound/vibration for my channel, I'm fine, than I won't play a sound nor vibrate at any time
How am I supposed to achieve that?
Edit - one solution is following:
Use two channels:
one for updating the notification
one for the final result notification.
This looks weird to me, I would assume that I can use one channel, set it up with sounds by default and use this channel. I should be able to define myself to play a sound or not, if the user allows me to play a sound (seems like I'm forced to play a sound currently). Otherwise I never play a sound of course. It looks like currently you need two channels for every service, that shows progress in the notification and plays a sound by default if finished. That's bad to explain to the user because you need two channels for the same action, on for the progress and one for the final result...

I was annoyed with the sound of my notifications. I did this.
.setSound(Uri.parse("android.resources://" + getPackageName() + "/" + R.raw.silence))
and this
.setOnlyAlertOnce(true)
Also note that you have to set them in the channel too.

Related

Android notification won't show up as a heads up notification

I am using the following code to show my notification:
NotificationCompat.Builder builder =
new NotificationCompat.Builder(context,
context.getString(R.string.notification_general_id))
.setSmallIcon(R.drawable.iit)
.setContentTitle("something")
.setContentText(notification)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true);
// https://stackoverflow.com/a/28251192/2287994
long time = new Date().getTime();
String tmpStr = String.valueOf(time);
String last4Str = tmpStr.substring(tmpStr.length() - 5);
int notificationId = Integer.parseInt(last4Str);
Log.d(TAG, "notificationId " + notificationId);
notificationManager.notify(notificationId, builder.build());
I create notification channel using the following code:
// for showing general notifications
NotificationChannel generalNotificationsChannel = new NotificationChannel(
getString(R.string.notification_general_id),
getString(R.string.notification_general_name),
NotificationManager.IMPORTANCE_HIGH
);
nearbyAnchorsChannel.setDescription(getString(R.string.notification_general_desc));
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
On Google Pixel 3a, the notification only vibrates and shows up as a blip on the top left. However, on the OnePlus 6, it shows up as a proper heads-up notification that we can immediately swipe or tap on. I tried looking through the settings of my Pixel 3a (it is Android 12) but I cannot find any option that I can change to enable a heads-up display of notifications. Tbh, I am not even sure if there is something wrong with my code or the phone I am testing it on. Is it because of my OnePlus 6's Android version (it is Android 11)? Or is it due to the code that I have written? If it is due to the former then can someone please explain to me how I can change settings on my Pixel 3a to show a proper swipeable heads-up notification?
My bad, when you change channel importance, you need to uninstall the app and install it again. That's why it worked on the OnePlus 6 (because I installed it after changing the notification importance) and not on the Google Pixel 3a (because I was still working with the same install)

Android notification is not showing as a message

The notification it self is working good, but not as I want. It vibrates and shows the icon defined but not as a Watsapp Notification and in the setCategory I put CATEGORY_MESSAGE but still, nothing!
on my App class i put :
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,CHANNEL_NAME,NotificationManager.IMPORTANCE_HIGH);
channel.setDescription(CHANNEL_DESC);
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
NotificationManager manager = getSystemService(NotificationManager.class);
assert manager != null;
manager.createNotificationChannel(channel);
}
Fragment :
private void T(String message){
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext(),CHANNEL_ID)
.setContentText(message)
.setContentTitle("Test")
.setColor(0xff123456)
.setSmallIcon(R.drawable.com_facebook_button_icon)
.setCategory(CATEGORY_MESSAGE)
.setPriority(PRIORITY_HIGH);
NotificationManagerCompat compat = NotificationManagerCompat.from(getApplicationContext());
compat.notify(1,mBuilder.build());
}
This is How I want it to notify :
This is how is current notifying
I'm using the SDK 27
After discussing with OP in chat, here's my best explanation about what could have happened:
A notification channel can only be created once, after which it becomes immutable to the app. It can only be tweaked by the user through the Settings. If someone follows the examples in the official docs first, they might create the channel with IMPORTANCE_DEFAULT. After this, even if they change the code later, the channel will remain at level 'High: Make Sound' and not be set to 'Urgent: Make Sound and pop on screen' as desired. Docs on importance level
The code in the question is perfectly fine, and should create a channel with the 'Urgent' level when installed for the first time. In any case, uninstalling the app manually and then installing it again will recreate the channels, setting the level to whatever is mentioned in the latest code.

Disable sound from NotificationChannel

Today I started targeting API 26 which forced me to use Notification Channels.
My problem is that now on each new notification (including updates to it) an annoying sound is played.
How can I disable this sound?
I tried replacing this sound with a custom mp3 sound in order to then pass it a mp3 with silence in it, but this is ignored.
I'm just adding a notification which is of very low priority, basically giving the user the option to perform some actions after he has interacted with the app. There's no reason to be loud, the user will know that he can refer to the notification because he has done a certain thing with the app which he knows that will cause a notification to appear.
The user will really start getting annoyed by that sound.
If you want to keep the importance of your channel and just remove the sound notificationChannel.setSound(null, null); seems to do the job.
EDIT:
Make sure to change the channel ID (and delete the old one) to have it applied to existing users. (Channels can be created, but never modified by the app, only the user can.)
(Update 2019-05: It gets worse with Android Q, there I'm even getting a sound when using NotificationManager.IMPORTANCE_LOW, at least in the Emulator...)
The solution is to use NotificationManager.IMPORTANCE_LOW and create a new channel for it. Once a channel is created, you can't change the importance (well, you can, but the new importance is ignored). The channel information appears to get stored permanently by the system and any channel created is only deleted when you uninstall the app. [Update: According to Ferran Negre's comment, you can delete the channel via nm.deleteNotificationChannel(nChannel.getId()); and recreate it with nm.createNotificationChannel(nChannel); but apparently there's a limitation that you can't create a channel with the same id of a deleted channel and expect to be able to apply different settings to the undeleted channel, see acoder's answer]
While previous Android versions played no sound back by default, this changed with Android O, but only when you target the API 26, that is, use Notification Channels. This is an inconsistency, well, actually, it's a bug:
The reason for this is that when you create a channel with NotificationManager.IMPORTANCE_DEFAULT (not soundworthy by default) Android will actually "somewhat" register it as NotificationManager.IMPORTANCE_HIGH (plays sound by default).
You can check this by going into the options of the notifications (long press on the notification entry), where you will get to read that it is of type NotificationManager.IMPORTANCE_HIGH and then disable the notification and then re-enable it. In this process it gets "downgraded" from the NotificationManager.IMPORTANCE_HIGH to the non-sounding, actually registered NotificationManager.IMPORTANCE_DEFAULT.
The bug has been submitted to the Android issue tracker, so you may want to star it (flagged by Google as "Won't Fix (Infeasible)", because... spoiled).
BTW, the new docs at https://developer.android.com/training/notify-user/channels
claim that the default behavior used to be that way, that default played a sound prior to Android 8.0, which is definitely not true. This is their list
User-visible importance level Importance Priority
(Android 8.0 and higher) (Android 7.1 and lower)
Urgent Makes a sound and appears as IMPORTANCE_HIGH PRIORITY_HIGH
a heads-up notification or PRIORITY_MAX
High Makes a sound IMPORTANCE_DEFAULT PRIORITY_DEFAULT
Medium No sound IMPORTANCE_LOW PRIORITY_LOW
Low No sound and does not appear IMPORTANCE_MIN PRIORITY_MIN
in the status bar
You can even see the mismatch between visibility importance high and notification importance high... I don't know why they are doing this. They definitely have a bug in their code.
Everything below the next line is obsolete, yet that bug mentioned there is still valid. My error there was to think that NotificationManager.IMPORTANCE_MIN is the next lower one from NotificationManager.IMPORTANCE_DEFAULT, but NotificationManager.IMPORTANCE_LOW is.
When you then go into the notification settings of the app via long-press-notification and all-channels button and toggle the switch for that channel off and on again, then it actually sets itself to NotificationManager.IMPORTANCE_DEFAULT and no sound will get played. I also noticed that after a crash it did get reset to NotificationManager.IMPORTANCE_HIGH
So basically the workaround is to use NotificationManager.IMPORTANCE_MIN. But you have to create a new channel so that this NotificationManager.IMPORTANCE_MIN is in effect, because it appears that you can't change the importance of an already existing channel once you have created it.
Update: Turns out the workaround with NotificationManager.IMPORTANCE_MIN has a drawback.
When you use that importance level then your notification no longer displays fully inside the notification drawer, but inserts itself in a new Notification Channel Group which is collapsed by default (and will collapse itself again each time the drawer is pulled down). What a bummer!
Update 2: Digging a bit deeper it turns out that it is as if it correctly registered it as NotificationManager.IMPORTANCE_DEFAULT, but somehow it magically got upgraded to NotificationManager.IMPORTANCE_HIGH, like it would when the user explicitly changes the setting from default to high. That one also gets reset to default after turning the notification off and then on again.
Well i will add a complete answer to help. If you read NotificationCompat code from androidx.
/**
* Silences this instance of the notification, regardless of the sounds or vibrations set
* on the notification or notification channel.
*/
public #NonNull Builder setNotificationSilent() {
mSilent = true;
return this;
}
So you have to use like this if you want remove sound AND vibration.
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
// no sound or vibration
.setNotificationSilent()
If you want remove sound only. This is the way.
// no sound
builder.setSound(null);
If you want remove viration only.
// no vibration
mChannel.setVibrationPattern(new long[]{ 0 });
mChannel.enableVibration(true);
NotificationCompat.Builder.setSilent(true)
This allows you to post a silent notification (no sound or vibration) regardless of the channel's importance setting.
Reference:
https://developer.android.com/reference/androidx/core/app/NotificationCompat.Builder#setSilent(boolean)
As far as I have seen, since API 26 (Oreo) it is not possible to change the sound of a notification after it was once created.
notificationManager.deleteNotificationChannel("channel_id"));
NotificationChannel notificationChannel = new NotificationChannel(
"channel_id", "channel_name",
NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setSound(null, null);
notificationManager.createNotificationChannel(notificationChannel);
Even deleting the channel before creation does not help.
Google documentation says:
android.app.NotificationManager public void deleteNotificationChannel(String channelId)
Deletes the given notification channel.
If you create a new channel with this same id, the deleted channel will be un-deleted with all of the same settings it had before it was deleted.
NotificationChannel#setSound() documentation states
Only modifiable before the channel is submitted to NotificationManager#createNotificationChannel(NotificationChannel)
Too bad that notificationBuilder.setSound(defaultSoundUri) does not work as well:
This method was deprecated in API level 26. Use NotificationChannel#setSound(Uri, AudioAttributes) instead.
Also using support library does not work. So sound is only settable once in the app and changing by the user is only possible in the settings of the notification. For me Ferran Negre's comment did not work. I do not understand why Google made this restriction. Too bad.
I have tested a lot of android devices,the following code works for me properly
Firstly, create a notificationBuilder, if your Build.Version is bigger than 26, please add a new channel.
private val notificationBuilder: NotificationCompat.Builder by lazy {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) NotificationCompat.Builder(context) else {
val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val channelId = "MUSIC"
val channelName = "音乐控制栏"
val importance = NotificationManager.IMPORTANCE_MIN
val channel = NotificationChannel(channelId, channelName, importance)
manager.createNotificationChannel(channel)
channel.enableLights(false)
channel.vibrationPattern = longArrayOf(0L)
channel.enableVibration(false)
channel.setSound(null, null)
NotificationCompat.Builder(context, channelId)
}
}
Secondly, init this notificationBuilder, and set sound null
notificationBuilder.setDefaults(Notification.DEFAULT_LIGHTS ).setVibrate( longArrayOf(0L)).setSound(null)
Thirdly,if build.version is bigger than 24, please set its priority.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
notificationBuilder.priority = NotificationManager.IMPORTANCE_MIN
}
Hope that works for you.
NotificationManager.IMPORTANCE_LOW
It produces no sound when notification is created as I need the same in my Music Application.
And yes if you have already created a notification channel then either you need to change the channel id or simply uninstall the previous application and install again.
For me the solution was to create group notification.
val builder = NotificationCompat.Builder(this)
.setGroupAlertBehavior(GROUP_ALERT_SUMMARY)
.setGroup("My Group")
.setGroupSummary(false)
.setDefaults(DEFAULT_ALL)
.setSound(null)
But in this case, if you send a new notification with a new ID, then it will be grouped with the previous notifications.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationChannel = NotificationChannel(
channelId.toString(), title,
NotificationManager.IMPORTANCE_DEFAULT
)
notificationChannel.setSound(null,null)
notificationChannel.enableVibration(false)
notificationChannel.description = body
if(notificationManager.getNotificationChannel(channelId.toString())==null) {
notificationManager.createNotificationChannel(notificationChannel)
}
if (data["sound"]?.equals("default", true) == true) {//if your app need contorl sound enable
RingtoneManager.getRingtone(
this,
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
).play()
}
if(pushShake.isTrue() ){//if your app need contorl vibarate enable
val vbmanager= getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
vbmanager.vibrate(VibrationEffect.createOneShot(500,VibrationEffect.DEFAULT_AMPLITUDE))
}
}
below code is about notification, but sound,vibrate will not play at API 26 ,so dont worry about setsound or setvibrate
notificationManager.notify(channelId.toInt(), notificationBuilder.apply {
setContentIntent(pendingIntent)
setSmallIcon(R.drawable.img_logo)
setTicker(title)
setNumber(data["badge"]?.toIntOrNull() ?: 0)
setBadgeIconType(NotificationCompat.BADGE_ICON_SMALL)
color = if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
resources.getColorMuteDepre(R.color.colorAccent2)
} else {
Color.parseColor("#ffffff")
}
setContentTitle(title)
setContentText(body)
setWhen(System.currentTimeMillis())
setAutoCancel(true)
setSound(null)
setVibrate(longArrayOf())
if (pushShake.isTrue() && data["sound"]?.equals("default", true) == true) {
setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
val vbmanager = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
vbmanager.vibrate(500)
}
}else{
if (data["sound"]?.equals("default", true) == true) {
setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
}
if (pushShake.isTrue() ) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
val vbmanager = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
vbmanager.vibrate(500)
}
}
}
setStyle(
NotificationCompat.BigTextStyle().bigText(body).setSummaryText(body).setBigContentTitle(
title
)
)
setPriority(NotificationCompat.PRIORITY_DEFAULT)
}.build())
As IMPORTANCE solution has the side effect of no notification popup, I got a final solution is:
adding a silent sound resource which downloaded from below repo
set sound for the channel with the silent sound resource.
https://github.com/anars/blank-audio/blob/master/1-second-of-silence.mp3
If the case is like mine, that I am forced to show a notification for background service and I don't really want to show any notification the solution that worked on 8.0 was:
.setPriority(NotificationManager.IMPORTANCE_NONE)
With this not only I didn't get the annoying sound every 5 minutes but also minimized the appearance of the notification itself.
On 8.1 I didn't have the problem with the sound with following:
.setPriority(NotificationManager.IMPORTANCE_MIN)
You can use 2 different notification channel to send notification depending on there priority to user.
If its a high priority notification the send it via
new NotificationChannel("Channel ID", "Channel Name", NotificationManager.IMPORTANCE_HIGH);
Your user will get sound and pop when they will receive a notification.
If you want to send less important notification then use this channel.
new NotificationChannel("Channel ID", "Channel Name", NotificationManager.IMPORTANCE_LOW);
Your user will get a notification with no sound and pop up.
check different priority from here - https://developer.android.com/reference/android/app/NotificationManager
No need to use .setSound(null, null)
just use below code
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,
getString(R.string.notification_channel_id))
.setContentTitle("Audio Recording")
.setContentText("recording in progress")
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setSmallIcon(R.mipmap.ic_launcher);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
getString(R.string.notification_channel_id), "AOD+", NotificationManager.IMPORTANCE_LOW
);
channel.setDescription("Call Recorder is running");
channel.setShowBadge(true);
channel.canShowBadge();
channel.setLightColor(Color.GREEN);
channel.enableVibration(false);
assert notificationManager != null;
notificationManager.createNotificationChannel(channel);
}
assert notificationManager != null;
startForeground(256/* must be greater than 0*/, notificationBuilder.build()); //I am using this for audio recording
//notificationManager.notify(0, notificationBuilder.build());
First you need to set
importance = NotificationManager.IMPORTANCE_LOW;
then
Notification n = builder.setPriority(Notification.DEFAULT_ALL).build();
n.defaults = 0;
n.defaults |= Notification.DEFAULT_VIBRATE;
NotificationManager.IMPORTANCE_LOW
This will work but also collapsed your notification.
NotificationManager.IMPORTANCE_LOW will work for sure
I faced the same issue in the 8.1 and made the below changes. Change the priority of the notification as LOW and it will disable the sound of notification.
NotificationManager.IMPORTANCE_LOW
The code is like following:
NotificationChannel chan1 = new NotificationChannel("default", "default", NotificationManager.IMPORTANCE_LOW);

How to send a notification with sound and vibration in do not disturb(DND) mode in android

How can I send a notification with sound and vibration when phone is in do not disturb mode on Android Devices.
I use the following code, and it is working when my application is currently in foreground.
PendingIntent contentIntent = PendingIntent.getActivity(this, NOTIFICATION_ID,
resultIntent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("Notification")
.setStyle(new NotificationCompat.BigTextStyle().bigText("You've received new message."))
.setContentText("You've received new message.");
// FOR SILENT MODE
AudioManager am = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
// For Normal mode
am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
am.setStreamVolume(AudioManager.STREAM_MUSIC, am.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);
mBuilder.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
// Set Vibrate, Sound and Light
int defaults = 0;
defaults = defaults | Notification.DEFAULT_LIGHTS;
// defaults = defaults | Notification.DEFAULT_VIBRATE;
// defaults = defaults | Notification.DEFAULT_SOUND;
mBuilder.setDefaults(defaults);
mBuilder.setSound(Uri.parse("android.resource://" + getPackageName()
+ "/" + R.raw.siren));
// Cancel the notification after its selection
mBuilder.setAutoCancel(true);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
I also want notifications with sound and vibration when my app is in background.
Generally speaking you can't. Even notification with MAX priority wont be shown in DND mode.
The possible workaround that I can imagine is to use android.permission.SYSTEM_ALERT_WINDOW to draw custom notification over system window (FB Messanger works in similar way) : Creating a system overlay window (always on top) .
But this method is suitable only in rare cases and most of the time it's a violation of Android UI/UX best practices.
Ok good news you are half way there.
I achieved this previously by using AudioManager & VIBRATOR_SERVICE (yea I know ;)
The idea is not to use NotificationCompat.Builder because it will rely on system settings and if device is in silent mode, it won't vibrate nor play sound. You have to manually play a sound using AudioManager & vibrate using VIBRATOR_SERVICE.
You are using AudioManager & setting the properties but you are never actually asking it to play the sound. So, in your code its never actually utilized.
Here's an example of how to play a sound using AudioManager, it will also ignore silent mode:
Here's an example of using VIBRATOR_SERVICE:
Combine these 2 approaches and ditch NotificationCompat.Builder
If you can get right permissions to change settings of device, then you could show notifications with sound and vibration at your apps. Also check this out.

How to stop heads-up notification being posted via Android Code?

I am building an android app that replaces the notification drawer and show notifications in its own window. I managed to show notifications on my drawer when they are posted by overriding onNotificationPosted() method. But, same notification is also shown by android. So,I want that notifications should be shown ONLY on my window, there are other apps who have done it,so it's not impossible. Please tell me how to override default behavior of android. Thanks in advance. :)
EDIT
What i want is to disable heads-up notification. Any solutions there?
In Oreo and above OS It is in the Notification channel Where you have to set the Priority any thing lesser than NotificationManager.IMPORTANCE_HIGH or some thing like this below stops the heads up banner.
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
CHANNEL_NAME,
NotificationManager.IMPORTANCE_DEFAULT)
On Pre-Oreo devices, the notification priority itself helps the system to show/hide the heads up banner.
Also remember when you make this change you have to delete the app and reinstall to see the change!
I used NotificationManager.IMPORTANCE_DEFAULT with setPriority(NotificationCompat.PRIORITY_DEFAULT) and it seems to work (Oneplus 3 and Note 8).
String channelId = "ch01";
String channelName = "Status";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
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 nb = new NotificationCompat.Builder(this, channelId);
nb.setSmallIcon(R.drawable.ic_logo);
nb.setContentTitle(notificationText);
nb.setContentText("");
nb.setContentIntent(mainActivityPendingIntent);
nb.setPriority(NotificationCompat.PRIORITY_DEFAULT);
nb.setOnlyAlertOnce(true);
nb.setOngoing(true);
nb.setWhen(System.currentTimeMillis());
Huh! Looks like Android provides no way to disable heads-up notification of other apps via code.
Here is a little hack!
So, what we need is, not show any heads-up notification from any other app. To solve this, we need to understand that at one time there could be only one heads-up notification on screen.
Hack is, send your own notification right after you listen any notification being posted i.e. in onNotificationPosted() of a NotificationListener subclass.
this.mNotificationManager.notify(12321, new Notification.Builder(this)
.setContentTitle("").setContentText("")
.setSmallIcon(R.drawable.transparent)
.setPriority(Notification.PRIORITY_DEFAULT)
.setFullScreenIntent(this.mBlankIntent, true)
.setAutoCancel(true)
.build());
It will replace the notification of the 3rd app with your almost blank notification. Oh wow! Wait!! This looks ugly.
Ofcourse, Now we need to remove this notification before the user could even see this.
Now that you know package name of the android. You can show cancel your notification some thing like this.
if(packageName.equals("com.my.package")){
mNotificationManager.cancel(12321);
return;
}
So, what we are doing is showing our notification, when any other heads up notification shows up, and then remove our own notification. All this happens so quick that user does not sees any heads-up notification, and for doing this, I did not needed to store the notification in memory even.
Set the IMPORTANCE to LOW and PRIORITY to LOW.
It work for me
var notificationChannel = NotificationChannel(channelId, "Call" , NotificationManager.IMPORTANCE_LOW)
var notification = NotificationCompat.Builder(context,channelId)
.setContentTitle("Calling")
.setContentText("Call")
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_LOW)

Categories

Resources