How to set NotificationChannel importance to urgent by program? - android

I want to implement chat notification() like whatsapp (Whatsapp don't know how but reset the Group Message channel importance (Android O) to Urgent).
All going good only i am not able to set NotificationChannel importance to Urgent programmatically.
Here is my work for the Notifications.
NotificationManager mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra(Const.Type.KEY, Const.Type.NOTIFICATION);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, "alert_001")
.setSmallIcon(R.drawable.ic_stat_s)
.setWhen(System.currentTimeMillis())
.setContentTitle("Booking Request")
.setContentText(content)
.setPriority(Notification.PRIORITY_MAX)
.setContentIntent(pendingIntent)
.setOngoing(false)
.setAutoCancel(true);
if (mNotificationManager != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(Const.Channel.Id.ALERT_001,
Const.Channel.Name.BOOKING_ALERT,
NotificationManager.IMPORTANCE_HIGH);
/* Here is no constant like NotificationManager.IMPORTANCE_URGENT
* and i can't even put the another integer value, It not obeying the rules*/
mNotificationManager.createNotificationChannel(channel);
mBuilder.setChannelId(channel.getId());
}
mNotificationManager.notify(1, mBuilder.build());
}
While i am changing the, JSON response for notification like below,
{
priority=high,
message=msgmsg,
source_lat=22.751552,
source_lng=75.895745,
user_detail={},
}
At least it is working like NotificationManager.IMPORTANCE_HIGH, But not like URGENT.
I don't know how whatsapp implemented that can override the URGENT importance even if user changes it manually.

There is a hack:
private String ensureChannelAudibility(String channelMainId, String channelName, Uri soundUri) {
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(App.instance);
List<NotificationChannel> channels = notificationManager.getNotificationChannels();
NotificationChannel existingChanel = null;
int count = 0;
for (NotificationChannel channel : channels) {
String fullId = channel.getId();
if (fullId.contains(channelMainId)) {
existingChanel = channel;
String[] numbers = extractRegexMatches(fullId, "\\d+");
if (numbers.length > 0) {
count = Integer.valueOf(numbers[0]);
}
break;
}
}
if (existingChanel != null) {
if (existingChanel.getImportance() < NotificationManager.IMPORTANCE_DEFAULT) {
notificationManager.deleteNotificationChannel(existingChanel.getId());
existingChanel = null;
}
}
if (existingChanel == null) {
String newId = channelMainId+'_'+(count+1);
NotificationChannel notificationChannel = new NotificationChannel(newId, channelName, NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(notificationChannel);
return newId;
} else {
return existingChanel.getId();
}
}
//Show the notification with channel id returned by the method above
public String[] extractRegexMatches(String source, String regex) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(source);
ArrayList<String> matches = new ArrayList<>();
while (matcher.find()) {
matches.add(matcher.group());
}
String[] result = new String[matches.size()];
matches.toArray(result);
return result;
}
Normally you can only set channel importance when creating it. Once the user changes it, you can not change it back programmatically. The code above tricks the system. It detects if channels importance is lower than needed and if it is, it deletes it and creates another one with a different id. Thus the system things that it's a different channel needed for something else.
So let's say you have a channel with "channelMainId" = wolf. A (wolf_1) channel will be created. Once the user changes it's settings, next channel will be (wolf_2), then
wolf_3, wolf_4 ... wolf_xxxxxxxxxxxx.

Please try this:
String channelId = "YOUR_CHANNEL_ID";
String channelName = "YOUR_CHANNEL_NAME";
int importance = NotificationManager.IMPORTANCE_HIGH;
final NotificationCompat.Builder noBuilder = new NotificationCompat.Builder(
this,channelId)
.setContentTitle("APP_NAME")
.setSmallIcon(//set any Icon)
.setContentText("TEXT")
.setAutoCancel(true);
final NotificationManager notificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
// for oreo-notification
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(
channelId, channelName, importance);
notificationManager.createNotificationChannel(mChannel);
}
Thanks

Related

FirebaseMessagingService push notification creation - how to set icon?

I want to set icon for my push notification which is created by FirebaseMessagingService. Problem is that these notifications are created by system internally (probably in function onStartCommand() which is final and I don't have access to it. I don't know from which source is icon for this notification set. Normally if you create notification you can set icon by NotificationManager, but this process is done internally by Firebase. Reason why I want to change icon is because my icon for app has transparent background (its vector drawable (.svg). But for some reason it is shown as square.
Is there any way how to modify notification icon inside FirebaseMessagingService?
Use this Function for display notification
public void showNotificationMessage(final String title, final String message,Intent intent) {
Random random = new Random();
NotificationManager notifManager = null;
if (notifManager == null) {
notifManager = (NotificationManager)mContext.getSystemService(Context.NOTIFICATION_SERVICE);
}
NotificationCompat.Builder mBuilder=null;
if (TextUtils.isEmpty(message))
return;
final int icon = R.mipmap.ic_launcher;
String notificationId = String.format("%04d", random.nextInt(10000));
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
final PendingIntent resultPendingIntent =
PendingIntent.getActivity(
mContext,
Integer.parseInt(notificationId),
intent,
PendingIntent.FLAG_CANCEL_CURRENT
);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = notifManager.getNotificationChannel("Test");
if (mChannel == null) {
mChannel = new NotificationChannel("Test", title, importance);
mChannel.enableVibration(true);
notifManager.createNotificationChannel(mChannel);
}
mBuilder = new NotificationCompat.Builder(mContext, "Test");
}else{
mBuilder = new NotificationCompat.Builder(mContext, "Test");
}
Notification notification;
notification = mBuilder.setTicker(title)
.setAutoCancel(true)
.setContentTitle(title)
.setContentIntent(resultPendingIntent)
//.setStyle(inboxStyle)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText(message)
.build();
NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(Integer.parseInt(notificationId), notification);
}

Bad notification for startForeground for Android 9 [duplicate]

After upgrading my phone to 8.1 Developer Preview my background service no longer starts up properly.
In my long-running service I've implemented a startForeground method to start the ongoing notification which is called in on create.
#TargetApi(Build.VERSION_CODES.O)
private fun startForeground() {
// Safe call, handled by compat lib.
val notificationBuilder = NotificationCompat.Builder(this, DEFAULT_CHANNEL_ID)
val notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.build()
startForeground(101, notification)
}
Error message:
11-28 11:47:53.349 24704-24704/$PACKAGE_NAMEE/AndroidRuntime: FATAL EXCEPTION: main
Process: $PACKAGE_NAME, PID: 24704
android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=My channel pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x42 color=0x00000000 vis=PRIVATE)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1768)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
invalid channel for service notification, apparently my old channel the DEFAULT_CHANNEL_ID is no longer appropriate for API 27 I assume. What would be the proper channel? I've tried to look through the documentation
After some tinkering for a while with different solutions i found out that one must create a notification channel in Android 8.1 and above.
private fun startForeground() {
val channelId =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createNotificationChannel("my_service", "My Background Service")
} else {
// If earlier version channel ID is not used
// https://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html#NotificationCompat.Builder(android.content.Context)
""
}
val notificationBuilder = NotificationCompat.Builder(this, channelId )
val notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.mipmap.ic_launcher)
.setPriority(PRIORITY_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build()
startForeground(101, notification)
}
#RequiresApi(Build.VERSION_CODES.O)
private fun createNotificationChannel(channelId: String, channelName: String): String{
val chan = NotificationChannel(channelId,
channelName, NotificationManager.IMPORTANCE_NONE)
chan.lightColor = Color.BLUE
chan.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
service.createNotificationChannel(chan)
return channelId
}
From my understanding background services are now displayed as normal notifications that the user then can select to not show by deselecting the notification channel.
Update:
Also don't forget to add the foreground permission as required Android P:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
Java Solution (Android 9.0, API 28)
In your Service class, add this:
#Override
public void onCreate(){
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
startMyOwnForeground();
else
startForeground(1, new Notification());
}
private void startMyOwnForeground(){
String NOTIFICATION_CHANNEL_ID = "com.example.simpleapp";
String channelName = "My Background Service";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Notification notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.drawable.icon_1)
.setContentTitle("App is running in background")
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
startForeground(2, notification);
}
UPDATE: ANDROID 9.0 PIE (API 28)
Add this permission to your AndroidManifest.xml file:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
The first answer is great only for those people who know kotlin, for those who still using java here I translate the first answer
public Notification getNotification() {
String channel;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
channel = createChannel();
else {
channel = "";
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, channel).setSmallIcon(android.R.drawable.ic_menu_mylocation).setContentTitle("snap map fake location");
Notification notification = mBuilder
.setPriority(PRIORITY_LOW)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
return notification;
}
#NonNull
#TargetApi(26)
private synchronized String createChannel() {
NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
String name = "snap map fake location ";
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel mChannel = new NotificationChannel("snap map channel", name, importance);
mChannel.enableLights(true);
mChannel.setLightColor(Color.BLUE);
if (mNotificationManager != null) {
mNotificationManager.createNotificationChannel(mChannel);
} else {
stopSelf();
}
return "snap map channel";
}
For android, P don't forget to include this permission
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
Works properly on Andorid 8.1:
Updated sample (without any deprecated code):
public NotificationBattery(Context context) {
this.mCtx = context;
mBuilder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setContentTitle(context.getString(R.string.notification_title_battery))
.setSmallIcon(R.drawable.ic_launcher)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setChannelId(CHANNEL_ID)
.setOnlyAlertOnce(true)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setWhen(System.currentTimeMillis() + 500)
.setGroup(GROUP)
.setOngoing(true);
mRemoteViews = new RemoteViews(context.getPackageName(), R.layout.notification_view_battery);
initBatteryNotificationIntent();
mBuilder.setContent(mRemoteViews);
mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (AesPrefs.getBooleanRes(R.string.SHOW_BATTERY_NOTIFICATION, true)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, context.getString(R.string.notification_title_battery),
NotificationManager.IMPORTANCE_DEFAULT);
channel.setShowBadge(false);
channel.setSound(null, null);
mNotificationManager.createNotificationChannel(channel);
}
} else {
mNotificationManager.cancel(Const.NOTIFICATION_CLIPBOARD);
}
}
Old snipped (it's a different app - not related to the code above):
#Override
public int onStartCommand(Intent intent, int flags, final int startId) {
Log.d(TAG, "onStartCommand");
String CHANNEL_ONE_ID = "com.kjtech.app.N1";
String CHANNEL_ONE_NAME = "Channel One";
NotificationChannel notificationChannel = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
notificationChannel = new NotificationChannel(CHANNEL_ONE_ID,
CHANNEL_ONE_NAME, IMPORTANCE_HIGH);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setShowBadge(true);
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.createNotificationChannel(notificationChannel);
}
Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
Notification notification = new Notification.Builder(getApplicationContext())
.setChannelId(CHANNEL_ONE_ID)
.setContentTitle(getString(R.string.obd_service_notification_title))
.setContentText(getString(R.string.service_notification_content))
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(icon)
.build();
Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
notification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);
startForeground(START_FOREGROUND_ID, notification);
return START_STICKY;
}
In my case, it's because we tried to post a notification without specifying the NotificationChannel:
public static final String NOTIFICATION_CHANNEL_ID_SERVICE = "com.mypackage.service";
public static final String NOTIFICATION_CHANNEL_ID_TASK = "com.mypackage.download_info";
public void initChannel(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.createNotificationChannel(new NotificationChannel(NOTIFICATION_CHANNEL_ID_SERVICE, "App Service", NotificationManager.IMPORTANCE_DEFAULT));
nm.createNotificationChannel(new NotificationChannel(NOTIFICATION_CHANNEL_ID_INFO, "Download Info", NotificationManager.IMPORTANCE_DEFAULT));
}
}
The best place to put above code is in onCreate() method in the Application class, so that we just need to declare it once for all:
public class App extends Application {
#Override
public void onCreate() {
super.onCreate();
initChannel();
}
}
After we set this up, we can use notification with the channelId we just specified:
Intent i = new Intent(this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pi = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID_INFO);
.setContentIntent(pi)
.setWhen(System.currentTimeMillis())
.setContentTitle("VirtualBox.exe")
.setContentText("Download completed")
.setSmallIcon(R.mipmap.ic_launcher);
Then, we can use it to post a notification:
int notifId = 45;
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(notifId, builder.build());
If you want to use it as foreground service's notification:
startForeground(notifId, builder.build());
Thanks to #CopsOnRoad, his solution was a big help but only works for SDK
26 and higher. My app targets 24 and higher.
To keep Android Studio from complaining you need a conditional directly around the notification. It is not smart enough to know the code is in a method conditional to VERSION_CODE.O.
#Override
public void onCreate(){
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
startMyOwnForeground();
else
startForeground(1, new Notification());
}
private void startMyOwnForeground(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
String NOTIFICATION_CHANNEL_ID = "com.example.simpleapp";
String channelName = "My Background Service";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Notification notification = notificationBuilder.setOngoing(true)
.setSmallIcon(AppSpecific.SMALL_ICON)
.setContentTitle("App is running in background")
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
startForeground(2, notification);
}
}
This worked for me. In my service class, I created the notification channel for android 8.1 as below:
public class Service extends Service {
public static final String NOTIFICATION_CHANNEL_ID_SERVICE = "com.package.MyService";
public static final String NOTIFICATION_CHANNEL_ID_INFO = "com.package.download_info";
#Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.createNotificationChannel(new NotificationChannel(NOTIFICATION_CHANNEL_ID_SERVICE, "App Service", NotificationManager.IMPORTANCE_DEFAULT));
nm.createNotificationChannel(new NotificationChannel(NOTIFICATION_CHANNEL_ID_INFO, "Download Info", NotificationManager.IMPORTANCE_DEFAULT));
} else {
Notification notification = new Notification();
startForeground(1, notification);
}
}
}
Note: Create the channel where you are creating the Notification for Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
Alternative answer: if it's a Huawei device and you have implemented requirements needed for Oreo 8 Android and there are still issues only with Huawei devices than it's only device issue, you can read https://dontkillmyapp.com/huawei
I had the same issue. The problem occurred when I used same channel id and notification id for two apps. So try with a unique notification id and channel id.
this maybe old but, incase someone had the same situation as I did.
for some reason, on Android 11 OnePlus Nord
Notification.Builder().Build()
crashes,
NotificationCompat.Builder().Build()
works fine.
Consider migrating to androidx.core.app.NotificationCompat.
If you're working with VPN library, these code will be help, I placed this inside onCreate(savedInstanceState: Bundle?)
NotificationChannelManager.createNotificationChannelIfNeeded(
activity,
channelName = "Chanel Name",
channelDescription = "Channel description"
)
Here is my solution
private static final int NOTIFICATION_ID = 200;
private static final String CHANNEL_ID = "myChannel";
private static final String CHANNEL_NAME = "myChannelName";
private void startForeground() {
final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
getApplicationContext(), CHANNEL_ID);
Notification notification;
notification = mBuilder.setTicker(getString(R.string.app_name)).setWhen(0)
.setOngoing(true)
.setContentTitle(getString(R.string.app_name))
.setContentText("Send SMS gateway is running background")
.setSmallIcon(R.mipmap.ic_launcher)
.setShowWhen(true)
.build();
NotificationManager notificationManager = (NotificationManager) getApplication().getSystemService(Context.NOTIFICATION_SERVICE);
//All notifications should go through NotificationChannel on Android 26 & above
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
CHANNEL_NAME,
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(NOTIFICATION_ID, notification);
}
Hope it will help :)

Notifications always making sound: setSound(null) is not wroking on OS >= 8

I am trying to group notifications and trigger sounds only for some of them using notification builder setSound() method, but it doesn't work. Each time I receive notifications it triggers the ringtone even though I call setSound(null)
This is my code:
TaskStackBuilder stackBuilder = TaskStackBuilder.create(getContext());
stackBuilder.addParentStack(getParentActivityClass());
Intent notificationIntent = intent == null ? new Intent() : new Intent(intent);
if (cls != null)
notificationIntent.setClass(getContext(), cls);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
stackBuilder.addNextIntentWithParentStack(notificationIntent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT);
InboxStyle style = new NotificationCompat.InboxStyle();
int mapId = subGroupId + groupId;
putGroupLine(mapId, text);
List<String> notifLines = groupedNotificationsMap.get(mapId);
for (int i = 0; i < notifLines.size(); i++) {
style.addLine(notifLines.get(i));
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String NOTIFICATION_CHANNEL_ID = "default";
String channelName = "Default";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName
, NotificationManager.IMPORTANCE_HIGH);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
if (alert == false) {
chan.setSound(null, null);
chan.setVibrationPattern(null);
}
else {
chan.setVibrationPattern(vibrate);
}
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.createNotificationChannel(chan);
}
NotificationCompat.Builder mBuilder;
mBuilder = new NotificationCompat.Builder(context, "default")
.setSmallIcon(getSmallIconResource())
.setAutoCancel(true);
int colorRes = getSmallIconColor();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mBuilder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_SUMMARY);
}
if (alert) {
mBuilder.setSound(getRingtone());
mBuilder.setVibrate( vibrate );
}
else {
mBuilder.setSound(null);
mBuilder.setVibrate(null);
}
Notification notif = mBuilder
.setContentTitle(title)
.setTicker(text)
.setContentText(text)
.setSmallIcon(getSmallIconResource())
.setStyle(style
.setBigContentTitle(title)
)
.setGroup("g" + groupId)
.setContentIntent(pendingIntent)
.build();
NotificationCompat.Builder summaryBiulder = new NotificationCompat.Builder(getContext(), "default")
.setContentTitle(title)
.setAutoCancel(true)
//set content text to support devices running API level < 24
.setContentText(text)
.setSmallIcon(getSmallIconResource())
//build summary info into InboxStyle template
.setStyle(new InboxStyle()
.setBigContentTitle(title)
.setSummaryText(title))
.setColor(colorRes)
//specify which group this notification belongs to
.setGroup("g" + groupId)
//set this notification as the summary for the group
.setGroupSummary(true)
.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_SUMMARY)
.setContentIntent(pendingIntent);
if (alert) {
summaryBiulder.setSound(getRingtone());
summaryBiulder.setVibrate( vibrate );
}
else {
summaryBiulder.setSound(null);
summaryBiulder.setVibrate(null);
}
Notification summaryNotification = summaryBiulder .build();
notif.flags |= Notification.FLAG_AUTO_CANCEL;
notif.flags |= Notification.FLAG_HIGH_PRIORITY;
notifManager.notify(subGroupId, notif);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notifManager.notify(groupId, summaryNotification);
}
Any suggestions?
Your problem is about notification importance
importance types
IMPORTANCE_MAX: unused
IMPORTANCE_HIGH: shows everywhere, makes noise and peeks
IMPORTANCE_DEFAULT: shows everywhere, makes noise, but does not visually intrude
IMPORTANCE_LOW: shows everywhere, but is not intrusive
IMPORTANCE_MIN: only shows in the shade, below the fold
IMPORTANCE_NONE: a notification with no importance; does not show in the shade
source
Although the other answers are useful, the main issue here was that the notification channel was already created. So, as stated in the docs, the behavior of a channel cannot be changed after creation (sound and vibration in this case). Only name and description can be changed, the user has full control over the rest.
In the code snippet,
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName,
NotificationManager.IMPORTANCE_HIGH);
Try replacing
NotificationManager.IMPORTANCE_HIGH to NotificationManager.IMPORTANCE_NONE
As according to Android developer documentation,
IMPORTANCE_HIGH
Higher notification importance: shows everywhere, makes noise and peeks. May use full screen intents.
So it may be making sound due to this.
Here's the link to other importance values available

Different notification sound not working in Oreo

I am facing some Notification related issue in Oreo Version only. I follow this link and successfully got custom sound after uninstall/install the app as he has suggested.
Now problem is that I want to use two custom sound in my app, For that, I have code like:
private void sendNotification(NotificationBean notificationBean) {
String textTitle = notificationBean.getTitle();
String alert = notificationBean.getMessage().getAlert();
int orderId = notificationBean.getMessage().getOrderId();
String notificationType = notificationBean.getMessage().getNotificationType();
String sound = notificationBean.getMessage().getSound();
Intent intent = new Intent(this, NavigationDrawerActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri soundUri;
if (notificationType.equals("Pending"))
soundUri = Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.sound);
else
soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, getString(R.string.app_name))
.setSmallIcon(R.drawable.ic_stat_name)
.setContentTitle(textTitle)
.setContentText(alert)
.setSound(soundUri)
.setContentIntent(pendingIntent)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
// 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.app_name);
String description = getString(R.string.app_name);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(getString(R.string.app_name), name, importance);
channel.setDescription(description);
AudioAttributes attributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
channel.enableLights(true);
channel.enableVibration(true);
channel.setSound(soundUri, attributes);
// 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);
}
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
// notificationId is a unique int for each notification that you must define
notificationManager.notify(101, mBuilder.build());
}
If I get notificationType = "Pending" then I want to use custom sound, otherwise DEFAULT sound but Here It is playing that sound which is played first-time (When I receive notification first time.).
I am getting this problem in OREO only. In all other devices its working fine.
Any help? Your help would be appreciated.
Problem:
It seems Notification Channel issue.
Solution:
Either you should create separate channel, or you should delete your own channel.
Strategy:
1) Create separate channel:
You may select this strategy if you want to persist multiple channels along with various configuration for your app.
To create separate channel, just provide unique channel ID while creating it.
i.e.:
NotificationChannel channel = new NotificationChannel(uniqueChannelId, name, importance);
2) Delete your existing channel and re-create it:
You may select this strategy if you want to persist only one channel along with updated configuration for your app.
To delete your own channel and re-create it, following may work fine:
NotificationManager mNotificationManager = getSystemService(NotificationManager.class);
NotificationChannel existingChannel = notificationManager.getNotificationChannel(channelId);
//it will delete existing channel if it exists
if (existingChannel != null) {
mNotificationManager.deleteNotificationChannel(notificationChannel);
}
//then your code to create channel
NotificationChannel channel = new NotificationChannel(channelId, name, importance);
I got hint to solve my problem from #Mehul Joisar's answer.
As he wrote:
Either you should create separate channel, or you should delete your
own channel.
I have created two separate channels for different sounds.
As I think, we cant change Notification Channel settings after once we
have created channel. We must have to remove and create new or else We
have to create separate channels for different settings.
Here I am sharing full code to help others.
private void sendNotification(NotificationBean notificationBean) {
String textTitle = notificationBean.getTitle();
String alert = notificationBean.getMessage().getAlert();
int orderId = notificationBean.getMessage().getOrderId();
String notificationType = notificationBean.getMessage().getNotificationType();
Intent intent = new Intent(this, NavigationDrawerActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Uri soundUri;
String channelName;
if (notificationType.equals("Pending")) {
channelName = getString(R.string.str_chef);
soundUri = Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.sound);
}
else {
channelName = getString(R.string.str_customer);
soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, channelName)
.setSmallIcon(R.drawable.ic_stat_name)
.setContentTitle(textTitle)
.setContentText(alert)
.setSound(soundUri)
.setContentIntent(pendingIntent)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
// 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.app_name);
String description = getString(R.string.app_name);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(channelName, name, importance);
channel.setDescription(description);
AudioAttributes attributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build();
channel.enableLights(true);
channel.enableVibration(true);
channel.setSound(soundUri, attributes);
// 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);
}
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
// notificationId is a unique int for each notification that you must define
notificationManager.notify(101, mBuilder.build());
}
NOTE: Must uninstall your app first and then test with this code.
Thank you.

startForeground fail after upgrade to Android 8.1

After upgrading my phone to 8.1 Developer Preview my background service no longer starts up properly.
In my long-running service I've implemented a startForeground method to start the ongoing notification which is called in on create.
#TargetApi(Build.VERSION_CODES.O)
private fun startForeground() {
// Safe call, handled by compat lib.
val notificationBuilder = NotificationCompat.Builder(this, DEFAULT_CHANNEL_ID)
val notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.build()
startForeground(101, notification)
}
Error message:
11-28 11:47:53.349 24704-24704/$PACKAGE_NAMEE/AndroidRuntime: FATAL EXCEPTION: main
Process: $PACKAGE_NAME, PID: 24704
android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=My channel pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x42 color=0x00000000 vis=PRIVATE)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1768)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
invalid channel for service notification, apparently my old channel the DEFAULT_CHANNEL_ID is no longer appropriate for API 27 I assume. What would be the proper channel? I've tried to look through the documentation
After some tinkering for a while with different solutions i found out that one must create a notification channel in Android 8.1 and above.
private fun startForeground() {
val channelId =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createNotificationChannel("my_service", "My Background Service")
} else {
// If earlier version channel ID is not used
// https://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html#NotificationCompat.Builder(android.content.Context)
""
}
val notificationBuilder = NotificationCompat.Builder(this, channelId )
val notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.mipmap.ic_launcher)
.setPriority(PRIORITY_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build()
startForeground(101, notification)
}
#RequiresApi(Build.VERSION_CODES.O)
private fun createNotificationChannel(channelId: String, channelName: String): String{
val chan = NotificationChannel(channelId,
channelName, NotificationManager.IMPORTANCE_NONE)
chan.lightColor = Color.BLUE
chan.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
service.createNotificationChannel(chan)
return channelId
}
From my understanding background services are now displayed as normal notifications that the user then can select to not show by deselecting the notification channel.
Update:
Also don't forget to add the foreground permission as required Android P:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
Java Solution (Android 9.0, API 28)
In your Service class, add this:
#Override
public void onCreate(){
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
startMyOwnForeground();
else
startForeground(1, new Notification());
}
private void startMyOwnForeground(){
String NOTIFICATION_CHANNEL_ID = "com.example.simpleapp";
String channelName = "My Background Service";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Notification notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.drawable.icon_1)
.setContentTitle("App is running in background")
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
startForeground(2, notification);
}
UPDATE: ANDROID 9.0 PIE (API 28)
Add this permission to your AndroidManifest.xml file:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
The first answer is great only for those people who know kotlin, for those who still using java here I translate the first answer
public Notification getNotification() {
String channel;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
channel = createChannel();
else {
channel = "";
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, channel).setSmallIcon(android.R.drawable.ic_menu_mylocation).setContentTitle("snap map fake location");
Notification notification = mBuilder
.setPriority(PRIORITY_LOW)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
return notification;
}
#NonNull
#TargetApi(26)
private synchronized String createChannel() {
NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
String name = "snap map fake location ";
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel mChannel = new NotificationChannel("snap map channel", name, importance);
mChannel.enableLights(true);
mChannel.setLightColor(Color.BLUE);
if (mNotificationManager != null) {
mNotificationManager.createNotificationChannel(mChannel);
} else {
stopSelf();
}
return "snap map channel";
}
For android, P don't forget to include this permission
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
Works properly on Andorid 8.1:
Updated sample (without any deprecated code):
public NotificationBattery(Context context) {
this.mCtx = context;
mBuilder = new NotificationCompat.Builder(context, CHANNEL_ID)
.setContentTitle(context.getString(R.string.notification_title_battery))
.setSmallIcon(R.drawable.ic_launcher)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setChannelId(CHANNEL_ID)
.setOnlyAlertOnce(true)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setWhen(System.currentTimeMillis() + 500)
.setGroup(GROUP)
.setOngoing(true);
mRemoteViews = new RemoteViews(context.getPackageName(), R.layout.notification_view_battery);
initBatteryNotificationIntent();
mBuilder.setContent(mRemoteViews);
mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (AesPrefs.getBooleanRes(R.string.SHOW_BATTERY_NOTIFICATION, true)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, context.getString(R.string.notification_title_battery),
NotificationManager.IMPORTANCE_DEFAULT);
channel.setShowBadge(false);
channel.setSound(null, null);
mNotificationManager.createNotificationChannel(channel);
}
} else {
mNotificationManager.cancel(Const.NOTIFICATION_CLIPBOARD);
}
}
Old snipped (it's a different app - not related to the code above):
#Override
public int onStartCommand(Intent intent, int flags, final int startId) {
Log.d(TAG, "onStartCommand");
String CHANNEL_ONE_ID = "com.kjtech.app.N1";
String CHANNEL_ONE_NAME = "Channel One";
NotificationChannel notificationChannel = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
notificationChannel = new NotificationChannel(CHANNEL_ONE_ID,
CHANNEL_ONE_NAME, IMPORTANCE_HIGH);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setShowBadge(true);
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.createNotificationChannel(notificationChannel);
}
Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
Notification notification = new Notification.Builder(getApplicationContext())
.setChannelId(CHANNEL_ONE_ID)
.setContentTitle(getString(R.string.obd_service_notification_title))
.setContentText(getString(R.string.service_notification_content))
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(icon)
.build();
Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
notification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);
startForeground(START_FOREGROUND_ID, notification);
return START_STICKY;
}
In my case, it's because we tried to post a notification without specifying the NotificationChannel:
public static final String NOTIFICATION_CHANNEL_ID_SERVICE = "com.mypackage.service";
public static final String NOTIFICATION_CHANNEL_ID_TASK = "com.mypackage.download_info";
public void initChannel(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.createNotificationChannel(new NotificationChannel(NOTIFICATION_CHANNEL_ID_SERVICE, "App Service", NotificationManager.IMPORTANCE_DEFAULT));
nm.createNotificationChannel(new NotificationChannel(NOTIFICATION_CHANNEL_ID_INFO, "Download Info", NotificationManager.IMPORTANCE_DEFAULT));
}
}
The best place to put above code is in onCreate() method in the Application class, so that we just need to declare it once for all:
public class App extends Application {
#Override
public void onCreate() {
super.onCreate();
initChannel();
}
}
After we set this up, we can use notification with the channelId we just specified:
Intent i = new Intent(this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pi = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID_INFO);
.setContentIntent(pi)
.setWhen(System.currentTimeMillis())
.setContentTitle("VirtualBox.exe")
.setContentText("Download completed")
.setSmallIcon(R.mipmap.ic_launcher);
Then, we can use it to post a notification:
int notifId = 45;
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(notifId, builder.build());
If you want to use it as foreground service's notification:
startForeground(notifId, builder.build());
Thanks to #CopsOnRoad, his solution was a big help but only works for SDK
26 and higher. My app targets 24 and higher.
To keep Android Studio from complaining you need a conditional directly around the notification. It is not smart enough to know the code is in a method conditional to VERSION_CODE.O.
#Override
public void onCreate(){
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
startMyOwnForeground();
else
startForeground(1, new Notification());
}
private void startMyOwnForeground(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
String NOTIFICATION_CHANNEL_ID = "com.example.simpleapp";
String channelName = "My Background Service";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Notification notification = notificationBuilder.setOngoing(true)
.setSmallIcon(AppSpecific.SMALL_ICON)
.setContentTitle("App is running in background")
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
startForeground(2, notification);
}
}
This worked for me. In my service class, I created the notification channel for android 8.1 as below:
public class Service extends Service {
public static final String NOTIFICATION_CHANNEL_ID_SERVICE = "com.package.MyService";
public static final String NOTIFICATION_CHANNEL_ID_INFO = "com.package.download_info";
#Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.createNotificationChannel(new NotificationChannel(NOTIFICATION_CHANNEL_ID_SERVICE, "App Service", NotificationManager.IMPORTANCE_DEFAULT));
nm.createNotificationChannel(new NotificationChannel(NOTIFICATION_CHANNEL_ID_INFO, "Download Info", NotificationManager.IMPORTANCE_DEFAULT));
} else {
Notification notification = new Notification();
startForeground(1, notification);
}
}
}
Note: Create the channel where you are creating the Notification for Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
Alternative answer: if it's a Huawei device and you have implemented requirements needed for Oreo 8 Android and there are still issues only with Huawei devices than it's only device issue, you can read https://dontkillmyapp.com/huawei
I had the same issue. The problem occurred when I used same channel id and notification id for two apps. So try with a unique notification id and channel id.
this maybe old but, incase someone had the same situation as I did.
for some reason, on Android 11 OnePlus Nord
Notification.Builder().Build()
crashes,
NotificationCompat.Builder().Build()
works fine.
Consider migrating to androidx.core.app.NotificationCompat.
If you're working with VPN library, these code will be help, I placed this inside onCreate(savedInstanceState: Bundle?)
NotificationChannelManager.createNotificationChannelIfNeeded(
activity,
channelName = "Chanel Name",
channelDescription = "Channel description"
)
Here is my solution
private static final int NOTIFICATION_ID = 200;
private static final String CHANNEL_ID = "myChannel";
private static final String CHANNEL_NAME = "myChannelName";
private void startForeground() {
final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
getApplicationContext(), CHANNEL_ID);
Notification notification;
notification = mBuilder.setTicker(getString(R.string.app_name)).setWhen(0)
.setOngoing(true)
.setContentTitle(getString(R.string.app_name))
.setContentText("Send SMS gateway is running background")
.setSmallIcon(R.mipmap.ic_launcher)
.setShowWhen(true)
.build();
NotificationManager notificationManager = (NotificationManager) getApplication().getSystemService(Context.NOTIFICATION_SERVICE);
//All notifications should go through NotificationChannel on Android 26 & above
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
CHANNEL_NAME,
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(NOTIFICATION_ID, notification);
}
Hope it will help :)

Categories

Resources