不可移除通知

21
在我的应用程序中,有一个在后台运行的服务。我想通知用户该服务正在运行。但是我需要确保用户无法删除通知 - 无论是通过按清除按钮还是通过在通知栏中滑动它。

enter image description here

这意味着我需要将我的通知显示在通知区域上方。
4个回答

65
这是可能的,但你实现它的方式取决于你所开发的API级别。
对于 API 级别低于 11 的版本,你可以设置 Notification.FLAG_NO_CLEAR。实现方法如下:
// Create notification
Notification note = new Notification(R.drawable.your_icon, "Example notification", System.currentTimeMillis());

// Set notification message
note.setLatestEventInfo(context, "Some text", "Some more text", clickIntent);

// THIS LINE IS THE IMPORTANT ONE            
// This notification will not be cleared by swiping or by pressing "Clear all"
note.flags |= Notification.FLAG_NO_CLEAR;
对于 API 级别在 11 及以上,或者使用了 Android Support Library 的情况下,可以按照以下方式实现:

对于 API 级别在 11 及以上,或者使用了Android Support Library的情况下,可以像这样实现:

Notification noti = new Notification.Builder(mContext)
    .setContentTitle("Notification title")
    .setContentText("Notification content")
    .setSmallIcon(R.drawable.yourIcon)
    .setLargeIcon(R.drawable.yourBigIcon)
    .setOngoing(true) // Again, THIS is the important line
    .build();

结合antew的帖子,我正好在寻找Notification.FLAG_ONGOING_EVENT。非常感谢。 - Kelib
你能试试这个安卓8.1.0吗?它是否工作?似乎它不起作用。 - MARSH

13

要创建不可删除的通知,只需使用 setOngoing(true);

NotificationCompat.Builder mBuilder =
                         new NotificationCompat.Builder(this)

                        .setSmallIcon(R.drawable.ic_service_launcher)

                        .setContentTitle("My title")

                        .setOngoing(true)  

                        .setContentText("Small text with details");

3

2

要创建不可移除的通知,只需使用 setOngoing(true);

要创建可移除的通知,只需使用 setOngoing(false);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接