Android 11 - Foreground service notification isn't visible - android

I have an android app that makes use of Foreground Services. My foreground service is supposed to display a notification.
I have updated one of my devices to Android 11 and the foreground service's notification is not being displayed. The foreground notification works as expected and is visible on all previous versions.
My code for starting a foreground service with a notification is as follows:
String channelName = "MyChannel";
NotificationChannel chan = new NotificationChannel("com.my.package", channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.createNotificationChannel(chan);
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.my_layout);
remoteViews.setImageViewResource(R.id.my_notification_id, R.drawable.my_icon);
remoteViews.setTextViewText(R.id.my_title, "Title");
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, "com.my.package");
notificationBuilder.setOngoing(true)
.setSmallIcon(R.drawable.ic_image_icon)
.setContentTitle("My Title")
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.setStyle(new android.support.v4.media.app.NotificationCompat.DecoratedMediaCustomViewStyle()
.setMediaSession(new MediaSessionCompat(context, MY_TAG).getSessionToken()))
.setColor(0x169AB9)
.setWhen(System.currentTimeMillis())
.setOnlyAlertOnce(true)
.setColorized(true);
PendingIntent contentIntent = PendingIntent.getActivity(context, MYMConstants.NOTIFICATION_GO_TO_ACTIVITY_REQUEST_CODE,
new Intent(context, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.setContent(remoteViews);
notificationBuilder.setContentIntent(contentIntent);
Notification notification = notificationBuilder.build();
startForeground(10000, notification);
The foreground service is started as follows:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(serviceIntent);
} else {
context.startService(serviceIntent);
}
I searched for the official documentation on Android 11 and underlying changes to Foreground services, but I couldn't find anything. Could someone help me out with this?

Nothing has changed the way how notifications are added to Foreground Service as part of Android 11.
I did find where the problem lies though. This piece of code above was causing the problem.
.setStyle(new android.support.v4.media.app.NotificationCompat.DecoratedMediaCustomViewStyle()
.setMediaSession(new MediaSessionCompat(context, MY_TAG).getSessionToken()))
Removing this fixed the issue.
To utilize setStyle(), we need to replace android.support.v4.media.app by androidx.media.app.

Related

Foreground service notification takes a few seconds to show up

Foreground service notification shows too slowly on Android 12. Used ContextCompat.startForegroundService(...) and mContext.startForegroundService(...). It still shows in 5-10 seconds.
Here is an example of my code:
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "Counting steps", NotificationManager.IMPORTANCE_DEFAULT);
channel.enableVibration(false);
channel.setSound(null, null);
channel.setShowBadge(false);
notificationManager.createNotificationChannel(channel);
}
}
The onStartCommand method:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String input = intent.getStringExtra("numberOfSteps");
createNotificationChannel();
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
Notification.Builder notificationBuilder = new Notification.Builder(this, CHANNEL_ID)
.setContentTitle("Counting steps")
.setContentText(input)
.setSmallIcon(R.drawable.ic_baseline_directions_walk_24)
.setContentIntent(pendingIntent);
startForeground(FOREGROUND_ID, notificationBuilder.build());
}
return START_STICKY;
}
How can I start or show a foreground service notification quickly?
Services that show a notification immediately
If a foreground service has at least one of the following
characteristics, the system shows the associated notification
immediately after the service starts, even on devices that run Android
12 or higher:
The service is associated with a notification that includes action
buttons. The service has a foregroundServiceType of
mediaPlayback, mediaProjection, or phoneCall. The service
provides a use case related to phone calls, navigation, or media
playback, as defined in the notification's category
attribute. The service has opted out of the behavior
change by passing FOREGROUND_SERVICE_IMMEDIATE into
setForegroundServiceBehavior() when setting up the
notification.
On Android 13 (API level 33) or higher, if the user denies the
notification permission, they still see notices related to foreground
services in the Foreground Services (FGS) Task Manager but don't see
them in the notification drawer.
See: Services that show a notification immediately
Java example code:
Notification.Builder notificationBuilder = new Notification.Builder(this, CHANNEL_ID)
.setContentTitle("Counting steps")
.setContentText(message)
.setSmallIcon(R.drawable.your_cool_icon)
.setContentIntent(pendingIntent);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
notificationBuilder.setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE);
}
Kotlin example:
val notificationBuilder: Notification.Builder =
Notification.Builder(this, CHANNEL_ID)
.setContentTitle("Notification title")
.setContentText("Content title")
.setSmallIcon(R.drawable.your_cool_icon)
.setContentIntent(pendingIntent)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
notificationBuilder.setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE)
}

Persistent notification android

I need to create a persistent notification - even on new Android versions.
I use a foreground service with (START_STICKY) to display the notification. The notification is created in the method onCreate() and from time to time I start again the foreground service - just in case it was killed.
This is how I create the notification:
String CHANNEL_ID = MainActivity.packageName+".notification";// The id of the channel.
CharSequence name = getString(R.string.app_name);// The user-visible name of the channel.
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
mChannel.setSound(null, null);
notificationManager.createNotificationChannel(mChannel);
}
NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(this, MainActivity.packageName+".notification");
Intent main = new Intent(this, MainActivity.class);
main.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, main, PendingIntent.FLAG_UPDATE_CURRENT);
// set intent so it does not start a new activity
Notification notification = nBuilder
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.icon)
.setWhen( System.currentTimeMillis())
.setContentTitle("my app")
.setContentText("my msg")
.setOngoing(true)
.setChannelId(MainActivity.packageName+".notification")
.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
//notificationManager.notify(StaticMembers.notifId, notification);
startForeground(StaticMembers.notifId+1, notification);
The notification is shown but on some phone models, after a few days the notification is not shown anymore, even if the service is still running.
What should I do? Is there something wrong with how I create the notification?
Should I check when the service runs if the notification is displayed and if not recreate it?
Thanks

Disable swipe removal notification in Android Oreo [duplicate]

This question already has answers here:
non removable notification
(4 answers)
Closed 4 years ago.
I am working on music application so i need to display notification on notification bar. for that i am using custom notification. The following is the code for notification for Android Oreo
String NOTIFICATION_CHANNEL_ID = "001";
RemoteViews notificationLayout = new RemoteViews(getPackageName(), R.layout.mynotification);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_LOW);
notificationChannel.setDescription("Channel description");
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(notificationChannel);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(MainActivity.this, NOTIFICATION_CHANNEL_ID);
notificationBuilder.setSmallIcon(R.drawable.exo_edit_mode_logo)
.setCustomContentView(notificationLayout)
.setAutoCancel(true)
.setPriority(Notification.PRIORITY_DEFAULT);
NotificationManagerCompat com = NotificationManagerCompat.from(this);
com.notify(001, notificationBuilder.build());
}
This code is working fine, but when swipe the notification from notification bar it will be removed. But my requirement is not remove when swipe the notification.
I tried with setAutoCancel(true) and setAutoCancel(false). But not working it will be removed. So how to stick the notification here.
Please guide me how to do this.
Thanks In Advance
use setOngoing(true) to achieve this
You have to add this setOngoing(true)
Try:
Notification.Builder builder = new Notification.Builder(this, CHANNEL_ID)
.setContentTitle(getString(R.string.app_name))
.setContentText("Text")
.setSmallIcon(R.mipmap.ic_launcher)
.setAutoCancel(false)
.setOngoing(true);
Notification notification = builder.build();

Detect when app is killed from recent apps list in android O and P

Use case is I have to send logout request to server when app get killed from recent lists. I use onTaskRemoved to handle that however in Android O and P I get notification bar saying "app is running" that I want to avoid. Here is how I run foreground service:
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
channelId = "my_service_channel_id";
String channelName = "My Foreground Service";
NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_LOW);
channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
channel.setSound(null, null);
notificationManager.createNotificationChannel(channel);
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this, channelId)
.setContentTitle("")
.setAutoCancel(true)
.setContentText("");
startForeground(NOTIFY_ID, builder.build());
//notificationManager.cancel(NOTIFY_ID); // It doesn't remove notification
//notificationManager.deleteNotificationChannel(channelId); // it causes crash
}
I already tried JobScheduler but onTaskRemoved doesn't get trigger. Any helps would be appreciated.

Notification does not vibrate when triggered

I am working on an app in android in which i wish to notify specific users about specific events. These notifications are made by using the the Firebase Cloud Messaging data-messages. When I send a data-message to the users client, the onMessageReceived-method is called and I can handle these messages as I wish.
Now I want to make the device vibrate in the very moment the messages arrives. Therefore, I tried to build a notification and set the vibration on it, however it does not vibrate at all..
I included the VIBRATE-permission in my applications Manifest as well.
Here is my Code to build the notification:
NotificationCompat.Builder mBuilder =
(NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_icon)
.setContentTitle("Content Title")
.setContentText("Content Text")
.setVibrate(new long[] {500,500,500,500,500,500,500,500,500});
Notification note = mBuilder.build();
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, note);
Have I missed anything?
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic)
.setContentTitle(context.getString(R.string.text))
.setContentText(context.getString(R.string.app_name))
.setContentIntent(contentIntent);
mBuilder.setVibrate(new long[]{500, 500});
mBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);
NotificationManager mNotifyMgr =
(NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
mNotifyMgr.notify(001, mBuilder.build());
This works for me.

Categories

Resources