Уведомление об обслуживании Android переднего плана не отображается
Я пытаюсь запустить службу переднего плана. Я получаю уведомление, что служба действительно начинается, но уведомление всегда подавляется. Я дважды проверял, что приложение может показывать уведомления в информации о приложении на моем устройстве. Вот мой код:
private void showNotification() {
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setAction(Constants.ACTION.MAIN_ACTION);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
Bitmap icon = BitmapFactory.decodeResource(getResources(),
R.mipmap.ic_launcher);
Notification notification = new NotificationCompat.Builder(getApplicationContext())
.setContentTitle("Revel Is Running")
.setTicker("Revel Is Running")
.setContentText("Click to stop")
.setSmallIcon(R.mipmap.ic_launcher)
//.setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false))
.setContentIntent(pendingIntent)
.setOngoing(true).build();
startForeground(Constants.FOREGROUND_SERVICE,
notification);
Log.e(TAG,"notification shown");
}
Вот единственная ошибка, которую я вижу по отношению:
06-20 12:26:43.635 895-930/? E/NotificationService: Suppressing notification from the package by user request.
Ответы
Ответ 1
Проблема заключалась в том, что я использую Android O, и для этого требуется дополнительная информация. Вот успешный код для android O.
mNotifyManager = (NotificationManager) mActivity.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) createChannel(mNotifyManager);
mBuilder = new NotificationCompat.Builder(mActivity, "YOUR_TEXT_HERE").setSmallIcon(android.R.drawable.stat_sys_download).setColor
(ContextCompat.getColor(mActivity, R.color.colorNotification)).setContentTitle(YOUR_TITLE_HERE).setContentText(YOUR_DESCRIPTION_HERE);
mNotifyManager.notify(mFile.getId().hashCode(), mBuilder.build());
@TargetApi(26)
private void createChannel(NotificationManager notificationManager) {
String name = "FileDownload";
String description = "Notifications for download status";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel mChannel = new NotificationChannel(name, name, importance);
mChannel.setDescription(description);
mChannel.enableLights(true);
mChannel.setLightColor(Color.BLUE);
notificationManager.createNotificationChannel(mChannel);
}
Ответ 2
Это из-за ограничений службы Android O bg.
Поэтому теперь вам нужно вызывать startForeground()
только для сервисов, которые были запущены с помощью startForegroundService()
и вызывать его через первые 5 секунд после запуска сервиса.
Вот руководство - https://developer.android.com/about/versions/oreo/background#services
Как это:
//Start service:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(new Intent(this, YourService.class));
} else {
startService(new Intent(this, YourService.class));
}
Затем создайте и покажите уведомление (с каналом, как предполагалось ранее):
private void createAndShowForegroundNotification(Service yourService, int notificationId) {
final NotificationCompat.Builder builder = getNotificationBuilder(yourService,
"com.example.your_app.notification.CHANNEL_ID_FOREGROUND", // Channel id
NotificationManagerCompat.IMPORTANCE_LOW); //Low importance prevent visual appearance for this notification channel on top
builder.setOngoing(true)
.setSmallIcon(R.drawable.small_icon)
.setContentTitle(yourService.getString(R.string.title))
.setContentText(yourService.getString(R.string.content));
Notification notification = builder.build();
yourService.startForeground(notificationId, notification);
if (notificationId != lastShownNotificationId) {
// Cancel previous notification
final NotificationManager nm = (NotificationManager) yourService.getSystemService(Activity.NOTIFICATION_SERVICE);
nm.cancel(lastShownNotificationId);
}
lastShownNotificationId = notificationId;
}
public static NotificationCompat.Builder getNotificationBuilder(Context context, String channelId, int importance) {
NotificationCompat.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
prepareChannel(context, channelId, importance);
builder = new NotificationCompat.Builder(context, channelId);
} else {
builder = new NotificationCompat.Builder(context);
}
return builder;
}
@TargetApi(26)
private static void prepareChannel(Context context, String id, int importance) {
final String appName = context.getString(R.string.app_name);
String description = context.getString(R.string.notifications_channel_description);
final NotificationManager nm = (NotificationManager) context.getSystemService(Activity.NOTIFICATION_SERVICE);
if(nm != null) {
NotificationChannel nChannel = nm.getNotificationChannel(id);
if (nChannel == null) {
nChannel = new NotificationChannel(id, appName, importance);
nChannel.setDescription(description);
nm.createNotificationChannel(nChannel);
}
}
}
Помните, что ваше уведомление переднего плана будет иметь то же состояние, что и другие уведомления, даже если вы будете использовать разные идентификаторы каналов, поэтому оно может быть скрыто как группа с другими. Используйте разные группы, чтобы избежать этого.
Ответ 3
Если ничего из вышеперечисленного не сработало, проверьте, не равен ли ваш идентификатор уведомления 0... СЮРПРИЗ !! это не может быть 0.
Большое спасибо @Luka Kama за этот пост
startForeground(0, notification); // Doesn't work...
startForeground(1, notification); // Works!!!
Ответ 4
если вы нацелены на API- FOREGROUND_SERVICE
Android 9 (Pie) уровня 28 и выше, чем вы должны дать разрешение FOREGROUND_SERVICE
в файле манифеста. перейдите по этой ссылке: https://developer.android.com/about/versions/pie/android-9.0-migration# БФА
Ответ 5
Я столкнулся с той же самой проблемой, и все же, уведомление не показывалось после того, как я следовал всем предложениям. Мне пришлось удалить приложение с устройства, чтобы установить его снова. (Samsung S9+).
Ответ 6
Для меня все было установлено правильно (также добавлено разрешение FOREGROUND_SERVICE для манифеста), но мне просто нужно было удалить приложение и переустановить его.
Ответ 7
В моем случае это было вызвано мной, используя IntentService
.
Короче говоря, если вы хотите использовать функцию переднего плана, то подкласс Service
.