锁定屏幕中的前台服务通知

问题描述 投票:0回答:1

我正在尝试获得前台服务。我的问题是我的通知没有出现在锁定屏幕中。我尝试将可见性设置为PUBLIC,但它不起作用。

@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);
}
android service push-notification android-notifications
1个回答
0
投票
notification.setOngoing(true)

使通知显示在锁定屏幕上。

代码

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();
© www.soinside.com 2019 - 2024. All rights reserved.