I'm trying to add a style to my push notification (in this case, I add a bold "WARNING!" text). It works when my app received a notification in foreground condition, but it doesn't when in background. Do I miss something here ?
val body = "WARNING! $notifBody"
val bodyBold: Spannable = SpannableString(body)
bodyBold.setSpan(StyleSpan(Typeface.BOLD), 0, 8, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
builder.setSmallIcon(R.drawable.ic_logo_home)
.setLargeIcon(
BitmapFactory.decodeResource(
this.resources,
R.drawable.ic_logo_home
)
)
.setContentIntent(pendingIntent)
.setStyle(NotificationCompat.BigTextStyle()
.setBigContentTitle(notifTitle)
.bigText(bodyBold))
.setDefaults(Notification.DEFAULT_VIBRATE)
builder.priority = NotificationCompat.PRIORITY_HIGH
notificationManager.notify(Random().nextInt(), builder.build())
Related
Is this a platform bug or some problem in my implementation? It appears to be regardless of importance level. Version of Android is 8.1.0. Target SDK is 22 (I am stuck on that unfortunately).
val defaultChannelId = AppConstants.NOTIFICATION_DEFAULT_ID
val defaultChannelName = "New Orders - high priority"
val defaultChannel = NotificationChannel(
defaultChannelId,
defaultChannelName,
NotificationManager.IMPORTANCE_HIGH
)
defaultChannel.setSound(defaultSound, attributes)
defaultChannel.description = "When a new order arrives"
val notificationManager = NotificationManagerCompat.from(this)
notificationManager.createNotificationChannel(defaultChannel)
On button click:
Notification appears:
val builder = NotificationCompat.Builder(requireContext(), AppConstants.NOTIFICATION_DEFAULT_ID).apply {
setContentTitle("New Order Received")
setContentText("Fetching order...$payload")
setSmallIcon(R.drawable.outline_receipt_white_24)
setSound(Uri.parse("android.resource://" + activity?.packageName + "/" + R.raw.notification_decorative))
setCategory(NotificationCompat.CATEGORY_STATUS)
priority = NotificationCompat.PRIORITY_HIGH
setProgress(0, 0, true)
}
val notificationManager = NotificationManagerCompat.from(requireContext())
notificationManager.notify(payload, builder.build())
Notification does not appear:
val builder = NotificationCompat.Builder(requireContext(), AppConstants.NOTIFICATION_DEFAULT_ID).apply {
setContentTitle("New Order Received")
setContentText("Fetching order...$payload")
setSound(Uri.parse("android.resource://" + activity?.packageName + "/" + R.raw.notification_decorative))
setCategory(NotificationCompat.CATEGORY_STATUS)
priority = NotificationCompat.PRIORITY_HIGH
setProgress(0, 0, true)
}
val notificationManager = NotificationManagerCompat.from(requireContext())
notificationManager.notify(payload, builder.build())
Is this a platform bug or some problem in my implementation?
Neither, assuming that you are implying that the bug is in Oreo. You were always supposed to supply a small icon to show in the status bar. There was a bug in older versions of Android whereby you could hack a Notification such that it would not show such an icon. Malware authors thought this was great, and Google eventually fixed it.
I am struggling with this problem for a banch days and cannot find proper way to do it.
I would like to set default channel settings (like sound on, lights on, vibration, lock screen notification etc.)
When I create a channel (already tried with different channel id and different package names) I always get channel with only vibration on - rest of stuff is off.
I try to create channel with this code (changing importance value makes no change in new channels):
object DefaultNotificationChannel {
#RequiresApi(Build.VERSION_CODES.O)
fun createChannel(applicationContext: Context) {
val notificationManager = applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + applicationContext.packageName + "/" + R.raw.notification)
createNotificationChannel(applicationContext, notificationManager, sound)
}
#TargetApi(Build.VERSION_CODES.O)
private fun createNotificationChannel(applicationContext: Context, notificationManager: NotificationManager, sound: Uri) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = applicationContext.getString(R.string.notification_channel_name)
val id = applicationContext.getString(R.string.default_notification_channel_id)
val importance = NotificationManager.IMPORTANCE_HIGH
val channel = NotificationChannel(id, name, importance)
channel.enableLights(true)
channel.lightColor = Color.RED
channel.enableVibration(true)
val attributes = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build()
channel.setSound(sound, attributes)
channel.enableVibration(true)
channel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
notificationManager.createNotificationChannel(channel)
}
}
}
I know that once channel is created the app cannot change its settings - thats why I already have tried with different ids and pacakge names.
I also have tried with application example from (Google Codelabs Notification Channels and Badges) but with the same results.
I already noticed that in some others phones everythig is ok, with Importance.HIGHT - all of switch are turned on - but not on my device.
When I install apps like Whatsapp or Viber, they channels have all settings already on - so I guess it is possible to do automatically.
I know I can always add button to open channel settings in my app, but it will be better to do it automatically when channel is registered.
Thanks in advance! :)
I am building Notification with remote views. I have given NotificationCompat.VISIBILITY_PUBLIC. but Notification is not showing on lock screen in Oreo.
My compileSdkVersion and targetSdkVersion is 27
remoteViews = new RemoteViews(getPackageName(), R.layout.player_noti_layout);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("default",
getString(R.string.player_channel),
NotificationManager.IMPORTANCE_LOW);
channel.setDescription("Notification, Play/pause & Next/Prev");
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
notificationmanager.createNotificationChannel(channel);
}
builder = new NotificationCompat.Builder(this, "default");
Notification foregroundNote;
// Set Icon
foregroundNote = builder.setSmallIcon(R.drawable.ic_radio)
.setTicker(getResources().getString(R.string.app_name))
.setAutoCancel(false).setOngoing(true)
.setContent(remoteViews)
.setContentTitle("app name").setContentText("").setWhen(0).setPriority(NotificationCompat.PRIORITY_MAX)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.build();
Help appreciated!!! Thanks
try this:
Notification.Builder.setVisibility(Notification.VISIBILITY_PUBLIC);
What I found working for me is in your notificationchannel you change the LockscreenVisibility to this
channel.LockscreenVisibility = NotificationVisibility.Public;
And in your NotificationCompat.Builder
.setVisibility(NotificationCompat.VisibilityPublic)
You do seem to be using a slightly different Syntax as for me I had to capitalise .SetVisibility
I hope this still helps.
PS: Keep in mind that your phone might not allow lockscreen notifications. This also happened to me where the code worked but my phone still didn't show the notifications. ;)
So I am making my app compatible with Oreo and facing issue with notification.
I added notification channel according to documentation and everything is working smooth except notification keep making sound on every posting, tried setting defaults to 0 as well.
I am testing my app in emulator, any help is highly appreciated.
Used this code for creating channel
NotificationCompat.Builder builder = new NotificationCompat.Builder(PlayerService.this, "channel_01")
.setAutoCancel(false)
.setContentIntent(pendingIntent)
.setContent(viewsSmall)
.setCustomBigContentView(viewsExpanded)
.setDeleteIntent(pSwipeToDismiss);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder.setVisibility(Notification.VISIBILITY_PUBLIC);
}
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
builder.setPriority(Notification.PRIORITY_MAX);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
/* Create or update. */
NotificationChannel channel = new NotificationChannel("channel_01",
"Playback Notification",
NotificationManager.IMPORTANCE_DEFAULT);
mNotificationManager.createNotificationChannel(channel);
mBuilder.setChannelId("channel_01");
}
final Notification notification = builder.build();
startForeground(Constants.NOTIFICATION_ID.FOREGROUND_SERVICE,notification);
Take a look at the notification channel settings (swipe your notification and press the settings icon under it and then select your channel). Those settings are set the first time you create the channel and then not modified unless you do it manually in the device (at least that is my experience from uninstalling and reinstalling my app to see what settings I get by default).
Basically, channel.setSound(null, null) will only have effect when you create the channel on a fresh installation. That might be what they try to explain in the official guide:
Attempting to create an existing notification channel with its original values performs no operation
If you tried to follow that guide and set NotificationManager.IMPORTANCE_HIGH and didn't use channel.setSound(null, null), the channel would get importance level Urgent Make sound and pop on screen with the default sound.
^Benjamin answer works but he is missing some important detail! You must change your channel ID each time you adjust your code or Oreo will not make the changes. Not sure why.
My code below and you can see where the chnage must be made with this <-------here
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelID = "My Channel I"; <-------here
String appName = mContext.getResources().getString(R.string.app_name);
NotificationCompat.Builder notificationCompatBuilder = new NotificationCompat.Builder(mContext );
notificationCompatBuilder
.setOngoing(true)
.setContentTitle(mContext.getResources().getString(R.string.app_name))
.setContentText(mContext.getString(R.string.clocked_in))
.setSmallIcon(R.drawable.ic_action_name)
.setChannelId(channelID)
.setSound(null);
NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel notificationChannel = new NotificationChannel(channelID, appName, NotificationManager.IMPORTANCE_LOW);
notificationChannel.setSound(null, null);
notificationManager.createNotificationChannel(notificationChannel);
notificationManager.notify(ONGOINGNOTIFICATION_ID, notificationCompatBuilder.build());
}
Replace your code with this
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
/* Create or update. */
NotificationChannel channel = new NotificationChannel("channel_01",
"Playback Notification",
NotificationManager.IMPORTANCE_LOW);
channel.setSound(null, null);
mNotificationManager.createNotificationChannel(channel);
mBuilder.setChannelId("channel_01");
}
My scene is the first time there is a sound, and the update notification does not require a sound.
I use this setOnlyAlertOnce() method
Reference: https://developer.android.com/training/notify-user/build-notification#Updating
Test pass version 26
I'm writing an app using notification. Google developer guidelines encourages developers to provide settings to customize the notifications (disable vibration, set notification sound...), so I am trying to disable vibration for notifications if the user set it that way.
I am using NotificationCompat.Builder to create the notification, like this:
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(Application.getContext())
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(Notification.PRIORITY_MAX)
.setSmallIcon(R.drawable.ic_launcher)
.setLargeIcon(largeIconBitmap)
.setAutoCancel(true)
.setContentIntent(resultPendingIntent)
.setContentTitle(title)
.setContentText(content);
I tried different ways to disable notifications:
notificationBuilder.setVibrate(null);
notificationBuilder.setVibrate(new long[]{0l, 0l});
notificationBuilder.setDefaults(Notification.DEFAULT_ALL | ~Notification.DEFAULT_VIBRATE);
notificationBuilder.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND);`
I also tried to build the notification and change values on the resulting object:
Notification notification = notificationBuilder.build();
notification.vibrate = null;
But the phone still vibrates when the notification appears.
How can I disable vibration for notifications?
After a long trial & error session, I think I finally understood what's wrong.
The problem lies in this instruction notificationBuilder.setDefaults(Notification.DEFAULT_ALL).
No matter what parameter you pass to notificationBuilder.setVibrate() after setting DEFAULT_ALL or DEFAULT_VIBRATE will be silently discarded. Someone at Google must have decided to give a higher precedence to setDefaults than to setVibrate.
This is how I ended up disabling vibration for notifications in my app:
notificationBuilder.setDefaults(Notification.DEFAULT_LIGHT | Notification.DEFAULT_SOUND)
.setVibrate(new long[]{0L}); // Passing null here silently fails
This works but doesn't feel right to initialize a new long[] just to disable the vibration.
In the year 2020:
Setting the importance of the notification channel to NotificationManager.IMPORTANCE_NONE worked for me.
They are not stop because you are use "setDefaults(Notification.DEFAULT_ALL)" so if you need to stop vibration and sound remove this line , or if you need to use the default sound and stop vibration I think you must use setDefaults(Notification.DEFAULT_SOUND) etc ...
You have 2 solutions with the notification channel.
Set a "fake" pattern to disable the vibration.
Set Importance flag, but less flexible (see https://developer.android.com/training/notify-user/channels#importance). Takes care, it will also impact some other stuff like priority...
As a result, you can use
NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
// no vibration
channel.setVibrationPattern(new long[]{ 0 });
channel.enableVibration(true);
Or
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
.setVibrate(null) works for me - and a better solution than creating a needless long[].
Result: device doesn't vibrate and no grumbling in LogCat either. :)
notification.vibrate = new long[] { -1 };
this code work for me.
Above solutions didnt work but adding mBuilder.setOnlyAlertOnce(true); to my notification builder solved my problem.
if (mBuilder == null) {
String channelId = "channel-id";
String channelName = "Channel Name";
int importance = NotificationManager.IMPORTANCE_MAX;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(
channelId, channelName, importance);
mChannel.setSound(null, null);
mChannel.enableVibration(false);
notificationManager.createNotificationChannel(mChannel);
}
mBuilder = new NotificationCompat.Builder(Application.context, channelId);
mBuilder.setSmallIcon(R.drawable.ic_ulakbel)
.setContentTitle("YOURTITLE")
.setAutoCancel(true)
.setColor(ContextCompat.getColor(Application.context, R.color.green))
.setColorized(true);
mBuilder.setChannelId(channelId);
mBuilder.setPriority(1);
mBuilder.setCustomContentView(notificationLayout);
mBuilder.setCustomBigContentView(notificationLayout);
mBuilder.setOnlyAlertOnce(true);
notificationManager.notify(1452, mBuilder.build());
}else{
Notification notification = mBuilder.build();
notification.flags = Notification.FLAG_ONGOING_EVENT;
notificationManager.notify(1452,notification);
}
private void removeSoundAndVibration(Notification notification) {
notification.sound = null;
notification.vibrate = null;
notification.defaults &= ~DEFAULT_SOUND;
notification.defaults &= ~DEFAULT_VIBRATE;
This code is from Notification Compat Api Class. This should work, add all these to your builder.
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Example Service Channel",
NotificationManager.IMPORTANCE_MIN
);
serviceChannel.setVibrationPattern(new long[]{ 0 });
serviceChannel.enableVibration(true);
serviceChannel.enableLights(false);
serviceChannel.setSound(null, null);
serviceChannel.setShowBadge(false); //
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
If you make IMPORTANCE_MIN that you can disabled vibration, if you make IMPORTANCE_DEFAULT it happens vibration so you can try IMPORTANCE_MIN
July 2022: I have tried everything in this thread, and the only thing that worked was Zhar's suggestion to set importance to low:
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
I am targeting Android API level 24.
setVibrate(new long[0]) works if you're targetting API 28. I'm working with chinese smartwatches running smartphone android roms so in the rest of the devices should work fine. Hope it helps!