1

I'm trying to achieve a foreground service. my problem is my notification doesn't appear in the lock screen. I try to set visibility to PUBLIC but it doesn't work.

@RequiresApi(api = Build.VERSION_CODES.O)
private String createNotificationChannel() {

    NotificationChannel notificationChannel =
            new NotificationChannel(
                    "channelId",
                    "channelName",
                    NotificationManager.IMPORTANCE_DEFAULT);
    notificationChannel.setDescription("channelDescription");

    notificationChannel.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC);

    NotificationManagerCompat service = NotificationManagerCompat.from(getBaseContext());
    service.createNotificationChannel(notificationChannel);

    return "myChannelId";
}

public void startForeground() {
    Intent notificationIntent = new Intent(this, HomeActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    String channelID = "";
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        channelID = createNotificationChannel();
    }

    Notification notification = new NotificationCompat.Builder(this, channelID)
            .setContentTitle(title)
            .setContentText(content)
            .setShowWhen(false)
            .setSmallIcon(R.drawable.ic_notification_small_icon)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setContentIntent(pendingIntent)
            .build();

    startForeground("notificationId", notification);
}
HamzaSamir
  • 61
  • 4

1 Answers1

0
notification.setOngoing(true)

makes the notification visible on your lock screen.

Code

Notification notification = new NotificationCompat.Builder(this, channelID)
.setContentTitle(title)
.setContentText(content)
.setShowWhen(false)
.setSmallIcon(R.drawable.ic_notification_small_icon)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setContentIntent(pendingIntent)
.setOngoing(true)
.build();

if that doesn't work check your device settings.

https://stackoverflow.com/a/26932991/9017620

Vince VD
  • 1,506
  • 17
  • 38