【问题标题】:Android: How to create an "Ongoing" notification?Android:如何创建“正在进行的”通知?
【发布时间】:2011-04-17 14:10:13
【问题描述】:

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

【问题讨论】:

    标签: android notifications


    【解决方案1】:

    如果你使用NotificationCompat.Builder,你可以使用:

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
    mBuilder.setOngoing(true); //this will make ongoing notification
    

    【讨论】:

    • 赞成,因为现在我们应该使用 Builder 创建通知。
    • 需要targetSDK为23
    • @Mahmoud 我以后如何关闭它?
    • NotificationManager mNotifyMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mNotifyMgr.cancel(mNotificationID);
    【解决方案2】:

    Notification.FLAG_ONGOING_EVENT 标志分配给您的Notification

    示例代码:

    yourNotification.flags = Notification.FLAG_ONGOING_EVENT;
    // Notify...
    

    如果您不熟悉 Notification API,请阅读 Android 开发者网站上的 Creating Status Bar Notifications

    【讨论】:

    • 另外你应该使用Service.startForeground而不是NotificationManager.notify()开始持续的通知
    • 不应该是|=,而不是=吗?
    • 当我正在进行的任务结束后,我将如何关闭通知?
    【解决方案3】:

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

    例如:

    notification.flags |= Notification.FLAG_ONGOING_EVENT;
    notification.flags |= Notification.FLAG_SHOW_LIGHTS;
    

    将同时设置两个标志,而:

    notification.flags = Notification.FLAG_ONGOING_EVENT;
    notification.flags = Notification.FLAG_SHOW_LIGHTS;
    

    只会设置 FLAG_SHOW_LIGHTS 标志。

    【讨论】:

      【解决方案4】:
      public static final int FLAG_ONGOING_EVENT
      

      自:API 级别 1
      如果此通知涉及正在进行的事情(例如电话),则将按位或位到标志字段中应设置的位。

      public static final int FLAG_FOREGROUND_SERVICE
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-29
        • 1970-01-01
        • 2021-03-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多