Android:如何创建"正在进行"的通知?

Roh*_*mar 50 notifications android

在此输入图像描述

你好,我如何创建像电池指示器的第一个永久通知?

Wro*_*lai 87

Notification.FLAG_ONGOING_EVENT为您的分配标志Notification.

示例代码:

yourNotification.flags = Notification.FLAG_ONGOING_EVENT;
// Notify...
Run Code Online (Sandbox Code Playgroud)

如果您不熟悉NotificationAPI,请阅读Android开发人员网站上的创建状态栏通知.

  • 此外,您应该使用`Service.startForeground`开始持续通知,而不是使用`NotificationManager.notify()` (9认同)
  • 不应该是`| =`,而不是`=`? (5认同)
  • 一旦我的持续任务结束,我将如何解除通知? (2认同)

Mah*_*hat 82

如果您正在使用NotificationCompat.Builder,您可以使用:

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
mBuilder.setOngoing(true); //this will make ongoing notification
Run Code Online (Sandbox Code Playgroud)

  • upvote因为现在我们应该使用Builder来创建通知. (3认同)

joe*_*ank 49

实际上建议使用按位或通知标志,而不是直接设置标志.这允许您一次设置多个标志.

例如:

notification.flags |= Notification.FLAG_ONGOING_EVENT;
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
Run Code Online (Sandbox Code Playgroud)

将立即设置两个标志,而:

notification.flags = Notification.FLAG_ONGOING_EVENT;
notification.flags = Notification.FLAG_SHOW_LIGHTS;
Run Code Online (Sandbox Code Playgroud)

只会设置FLAG_SHOW_LIGHTS标志.


Ale*_*dam 5

public static final int FLAG_ONGOING_EVENT
Run Code Online (Sandbox Code Playgroud)

因为: API 级别 1
位将被按位或运算到标志字段中,如果此通知涉及正在进行的某事(如电话),则应设置该位。

public static final int FLAG_FOREGROUND_SERVICE
Run Code Online (Sandbox Code Playgroud)

因为: API 级别 5 位将按位或运算到标志字段中,如果此通知表示当前正在运行的服务,则应设置该位。