startForeground() need to create NotificationChannel so it will show badge number 1 on Launcher icon in Oreo devices
How can i hide/disable it programmatically?
Because Galaxy S8(Oreo) display badge number 1.
And Android 8.0 emulator also display dot.
This is how i am doing now. But setShowBadge(false) not works
EDIT1:
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationChannel tmpC = new NotificationChannel(id, "basic", NotificationManager.IMPORTANCE_MIN);
tmpC.setShowBadge(false);
manager.createNotificationChannel(tmpC);
Notification notification = new NotificationCompat.Builder(this, id)
.setChannelId(id)
.setAutoCancel(true)
.build();
startForeground(getPackageName().hashCode(), notification);
This answer is correct, but the point is you have to remove old version of the application by hands from Android "Applications" menu and install new version with mChannel.setShowBadge(false) on the clean device to get it working. An installation over the old version (where mChannel.setShowBadge(false) was absent) will not lead to the changing of the behaviour concerned with this badge.
all you need to do is calling setShowBadge(false) on your NotificationChannel object.
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Create notification channel.
NotificationChannel channel = new NotificationChannel({channel_id}, {name}, {importance});
mChannel.setShowBadge(false); // Disable badges for this notification channel.
mNotificationManager.createNotificationChannel(mChannel);
// Create notification and use channel
Notification notification = new NotificationCompat.Builder(context, {channel_id})
...
.build();
// notify
mNotificationManager.notify({notification_id}, notification)
Check out Modify a Notification Badge.
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);
}
setShowBadge(false) it is working
Related
My code:
// 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 = "channel_name";
String description = "channel_description";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(default_notification_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);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, default_notification_channel_id)
.setSmallIcon(R.drawable.logo_mobile_main_btn)
.setContentTitle("textTitle")
.setContentText("textContent")
.setStyle(new NotificationCompat.BigTextStyle().bigText("Much longer text that cannot fit one line.Much longer text that cannot fit one line.Much longer text that cannot fit one line."))
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
// notificationId is a unique int for each notification that you must define
notificationManager.notify(( int ) System. currentTimeMillis () , builder.build());
Problem: display only "textTitle" and "textContent"
I Expected: display bigText
Do I wrong something ?
It's problems about version change and now I fixed!.
I'm working with notification channels and as standard I want to enable sound for notification. I set sound in NotificationChannel options, but it's disabled. I also tried to set Audio in the NotificationCompat.Builder but this either didn't worked.
Ps: I don't know if my phone is the problem, I have an Redmi Note 7 with Android 9 and MIUI.
I've tried in the Channel options, NotificationCompat.Builder, both and each once solo, but it didn't worked. But if I turn the option in the Channel settings on it works but I don't want that the user needs to do that.
String CHANNEL_ID = "coin_master_item_generator";
CharSequence CHANNEL_NAME = "Item Generator Coin Master";
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
channel.setDescription("Notifies when Items are generated");
channel.enableVibration(true);
channel.setVibrationPattern(new long[]{2000,1000});
channel.enableLights(true);
channel.setLightColor(Color.WHITE);
channel.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION),audioAttributes);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Item Generator")
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentText("New Items generated");
notificationManager.notify(1524,builder.build());
In MI Note 5 Pro which has latest MI UI 10.0 with Oreo, so when I try to send push notification by default sound is disable, so i am not able to enable sound programmatically when I am creating a channel for that.
In other Oreo devices notification sound is coming but in MI custom Oreo OS Sound is by default disable
Let me show my code for notification :
var intent = Intent(mContext, HomeActivity::class.java)
intent.putExtra(Constants.EXTRA_FROM_NOTIFICATION, true)
var pendingIntent = PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
var uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
var mBuilder = NotificationCompat.Builder(mContext, NOTIFICATION_CHANNEL_ID)
.setContentTitle(mContext.getString(R.string.app_name))
.setContentText(mFirstContactName + " : " + mListChatWindow[0].message)
.setPriority(if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) NotificationManager.IMPORTANCE_HIGH else Notification.PRIORITY_HIGH)
.setContentIntent(pendingIntent)
.setSound(uri)
.setSmallIcon(R.drawable.ic_app_icon)
.setColor(ContextCompat.getColor(mContext, R.color.colorPrimary))
.setVibrate(longArrayOf(0, 100, 1000, 300))
.setAutoCancel(true)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
var channel = NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", NotificationManager.IMPORTANCE_HIGH)
channel.description = "NOTIFICATION_DESCRIPTION"
channel.lightColor = Color.LTGRAY
channel.enableVibration(true)
channel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
val attributes = AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_NOTIFICATION).build()
channel.setSound(uri, attributes)
var notificationManager = mContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
var notificationManager = NotificationManagerCompat.from(mContext)
notificationManager.notify(NOTIFICATION_CHAT_ID, mBuilder.build())
I am also set channel.setSound(uri, attributes) in cannel but sound not coming
Here is the screenshot of Notification channel see there sound icon is disabled, how to enable?
Plz help
I had similar problem in MIUI Global 10.1 with oreo but it was only while using custom sound and not like yours, default sound. Any way let me explain how I solve it and hope it may solve yours.
First thing to consider is where the registration of notification channel is executed. It must be executed in Application.onCreate so that the channel is created even before the notification arrives. I was doing it in onMessageReceived.
Second as I said it was working for default notification sound and not for custom one, I inserted below code while creating notification channel and it worked.
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,CHANNEL_ID);
if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.O) {
notificationBuilder.setDefaults(Notification.DEFAULT_SOUND); // This line did the magic for me.
Uri sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.sound_notification_plucky);
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
CharSequence name = "MyChild";
String description = "All MyChild messages";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, name, importance);
notificationChannel.setDescription(description);
notificationChannel.enableVibration(true);
notificationChannel.setSound(sound, audioAttributes);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(notificationChannel);
}
I'm facing same issue and still didn't get satisfying answer, but till that time we can workaround it like so:
final Uri NOTIFICATION_SOUND = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
RingtoneManager.getRingtone(context, NOTIFICATION_SOUND).play();
You need to call this after:
notificationManager.notify(notificationId, notification);
This way you will always get sound playing even if "allow sound" was turned off for your App, and the sound played will be from the system not media (expected behavior from the notifications).
And to avoid having two sounds playing at once (for the devices that don't have this issue), you can turn the sounds off like so:
1- For the Builder:
notificationBuilder.setContentTitle(title)
.set.....
.set.....
.setSound(null);
2- For the channel:
channel.setSound(null, null);
mBuilder.setPriority(NotificationCompat.PRIORITY_HIGH)
This line of code is worked for me it enables all notification settings.
I am trying to add custom sound to notification. Following is my code:
notificationSoundUri = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.error);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("default",
"YOUR_CHANNEL_NAME",
NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("YOUR_NOTIFICATION_CHANNEL_DISCRIPTION");
mNotificationManager.createNotificationChannel(channel);
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, "default")
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
.setSmallIcon(R.mipmap.ic_launcher) // notification icon
.setContentTitle("BATTERY FULL") // title for notification
.setContentText("Battery is full. Please plug out the charger. Overcharging may decrease battery life span.")// message for notification
.setSound(notificationSoundUri) // set alarm sound for notification
.setAutoCancel(true); // clear notification after click
mNotificationManager.notify(1, mBuilder.build());
This code is working in pre-lollipop devices and not on Marshmallow. In Marshmallow, it is using phone's default notification sound. I am assuming this problem is for lollipop and higher devices. What am I missing here?
Had this issue for a few tries, it looks like NotificationCompat misses a method for sound on between androids 21 and 25, for notification to work you need to set the sound as this
val builder: Notification.Builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Notification.Builder(this, channelId1)
} else {
Notification.Builder(this)
}
...
val audioAttr = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_ALARM).build()
builder.setSound(
notification1Sound(), // custom uri
audioAttr)
I don't support versions prior lollipop so this works for me, for older version you might need to add a second version check
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder.setSound(
notification1Sound(),
audioAttr
)
} else {
builder.setSound(notification1Sound(), AudioManager.STREAM_ALARM)
}
You have to use Notification Channel whit Android O (https://developer.android.com/training/notify-user/channels).
This work only on API 26+ because the NotificationChannel class is new and not in the support library.
builder.setStyle(new NotificationCompat.InboxStyle());
The full code:
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Notifications Example")
.setContentText("This is a test notification");
Intent notificationIntent = new Intent(this, MenuScreen.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
builder.setAutoCancel(true);
builder.setLights(Color.BLUE, 500, 500);
long[] pattern = {500,500,500,500,500,500,500,500,500};
builder.setVibrate(pattern);
builder.setStyle(new NotificationCompat.InboxStyle());
Use these lines of code for custom sound
URI uri=Uri.parse("android.resource://"+context.getPackageName()+"/"+R.raw.FILE_NAME);//Here is FILE_NAME is the name of file that you want to play
builder.setSound(uri);
Don't forget to add notification channel
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
#SuppressLint("WrongConstant")
NotificationChannel channel = new NotificationChannel("XYZ", "ABC",NotificationManager.IMPORTANCE_MAX);
mNotificationManager.createNotificationChannel(channel);
}
mNotificationManager.notify(0, mBuilder.build());
Couple Android O notification questions:
1) I have created a Notification Channel (see below), am calling the builder with .setChannelId() (passing in the name of the channel I created, "wakey"; and yet, when I run the app, I get a message that I've failed to post a notification to channel "null". What might be causing this?
2) I suspect the answer to #1 can be found in the "log" that it says to check, but I've checked logcat & don't see anything about notifications or channels. Where is the log that it says to look in?
Here's the code I'm using to create the channel:
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence name = context.getString(R.string.app_name);
String description = "yadda yadda"
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL, name, importance);
channel.setDescription(description);
notificationManager.createNotificationChannel(channel);
Here's the code to generate the notification:
Notification.Builder notificationBuilder;
Intent notificationIntent = new Intent(context, BulbActivity.class);
notificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); // Fix for https://code.google.com/p/android/issues/detail?id=53313
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
Intent serviceIntent = new Intent(context, RemoteViewToggleService.class);
serviceIntent.putExtra(WakeyService.KEY_REQUEST_SOURCE, WakeyService.REQUEST_SOURCE_NOTIFICATION);
PendingIntent actionPendingIntent = PendingIntent.getService(context, 0, serviceIntent, PendingIntent.FLAG_CANCEL_CURRENT);
_toggleAction = new Notification.Action(R.drawable.ic_power_settings_new_black_24dp, context.getString(R.string.toggle_wakey), actionPendingIntent);
notificationBuilder= new Notification.Builder(context)
.setContentTitle(context.getString(R.string.app_name))
.setContentIntent(contentIntent)
.addAction(_toggleAction);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
notificationBuilder.setChannelId(NOTIFICATION_CHANNEL);
}
notificationBuilder.setSmallIcon(icon);
notificationBuilder.setContentText(contentText);
_toggleAction.title = actionText;
int priority = getNotificationPriority(context);
notificationBuilder.setPriority(priority);
notificationBuilder.setOngoing(true);
Notification notification = notificationBuilder.build();
notificationManager.notify(NOTIFICATION_ID, notification);
And here's the warning I'm getting:
I think I have learned a couple things that all add up to an answer:
I was using an emulator device, with an image that did not include the Play Store.
The version of Google Play Services on the image was not the latest, so I should have been getting a notification telling me I needed to upgrade. Since that notification didn't get applied to a channel, it didn't appear.
If I set logcat in Android Studio to "No Filters" instead of "Show only selected application", then I found the logs that pointed out that the notification in question was the Play Services "update needed" notification.
So, I changed to a image with the Play Store included, and it showed the notification properly (maybe the channel for that notification was to be set by the Play Store?), let me update to the latest Google Play Services, and I haven't seen that warning since.
So, long story short (too late) - with Android O, if you are using Google Play Services & testing on the emulator, choose an image with the Play Store included, or ignore the toast (good luck on that one!).
I had the same problem, and resolved it by using the constructor
new Notification.Builder(Context context, String channelId), instead of the one which is deprecated onAPI levels >=26 (Android O) :
new NotificationCompat.Builder(Context context)
The following code won't work if your notificationBuilder is built using the deprecated constructor :
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
notificationBuilder.setChannelId(NOTIFICATION_CHANNEL);}
First create the notification channel:
public static final String NOTIFICATION_CHANNEL_ID = "4565";
//Notification Channel
CharSequence channelName = NOTIFICATION_CHANNEL_NAME;
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, importance);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(notificationChannel);
then use the channel id in the constructor:
final NotificationCompat.Builder builder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID)
.setDefaults(Notification.DEFAULT_ALL)
.setSmallIcon(R.drawable.ic_timers)
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
.setSound(null)
.setChannelId(NOTIFICATION_CHANNEL_ID)
.setContent(contentView)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setLargeIcon(picture)
.setTicker(sTimer)
.setContentIntent(pendingIntent)
.setAutoCancel(false);
You gotta create a channel before.
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
// 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);
}
}
public void notifyThis(String title, String message) {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.green_circle)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
// notificationId is a unique int for each notification that you must define
notificationManager.notify(0, mBuilder.build());
}
Finally you call this method:
createNotificationChannel();
notifyThis("My notification", "Hello World!");
create a notification using following code :
Notification notification = new Notification.Builder(MainActivity.this)
.setContentTitle("New Message")
.setContentText("You've received new messages.")
.setSmallIcon(R.mipmap.ic_launcher)
.setChannelId(channelId)
.build();
not using :
Notification notification = new NotificationCompat.Builder(MainActivity.this)
.setContentTitle("Some Message")
.setContentText("You've received new messages!")
.setSmallIcon(R.mipmap.ic_launcher)
.setChannel(channelId)
.build();
You have to create a NotificationChannel first
val notificationChannel = NotificationChannel("channelId", "channelName", NotificationManager.IMPORTANCE_DEFAULT)
notificationManager.createNotificationChannel(notificationChannel);
This is the only way to show notification for API 26+
I was facing the same problem. It got resolved by creating a NotificationChannel and adding that newly created channel with the notification manager.
I would also like to add that you will receive this error if you're using Build tools v26+:
app/build.grade:
compileSdkVersion 26
buildToolsVersion "26.0.2"
defaultConfig {
targetSdkVersion 26
Downgrading to lowest version should work fine.