【问题标题】:Swipe dismissing service notification滑动关闭服务通知
【发布时间】:2014-12-16 11:42:51
【问题描述】:

认为这根本不是问题,但仍然如此。 无论我做什么,我的服务通知都不想滑动关闭。

我有一个进度通知,它是使用 startForeground(id, Notification) 在服务中启动的。 这是我的构建方式:

public Notification createErrorNotification(String message) {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext());

    Intent showAppIntent = new Intent(getApplicationContext(), MainActivity.class);
    showAppIntent.setAction(Intent.ACTION_MAIN);
    showAppIntent.addCategory(Intent.CATEGORY_LAUNCHER);
    PendingIntent pendingShowAppIntent = PendingIntent.getActivity(getApplicationContext(), 10,
            showAppIntent, PendingIntent.FLAG_CANCEL_CURRENT);


    builder.setContentTitle(getString(R.string.label_download_error))
            .setWhen(0)
            .setContentText(message)
            .setContentIntent(pendingShowAppIntent)
            .setAutoCancel(true)
            .setOngoing(false)
            .setSmallIcon(R.drawable.ic_launcher);

    return builder.build();
}

在某些时候,如果发生错误,我会用描述的错误通知替换我的进度通知,禁用“正在进行”和其他内容。 我也完全停止服务:

private void stopService() {
    stopSelf();
    taskThread.stopLooper();
    downloadHandler.stopExecution();
    downloadHandler = null;
    taskThread = null;
}

然后调用

stopForeground(false);

false - 因为我希望通知保留在屏幕上并被用户关闭。 但是滑动关闭根本不起作用。

如果我调用 stopForeground(true) - 通知被正确删除。

有人知道我在这里做错了什么吗?

【问题讨论】:

  • 在调用 stopForeground(true) 之后,尝试更新通知,通过创建一个带有选项 setCanceble(true) 和相同通知 ID 的新通知,
  • NotificationCompat.Builder 没有方法 'setCancelable'
  • 你可以在我的代码 sn-p 中看到,设置了 autoCancel
  • 您是否将 setAutoCancel 设置为 new 通知,而不是旧通知?
  • 我是怎么做到的:我调用 stopForeground(true),取消通知 mNotificationManager.cancel(NOTIFICATION_ID),然后显示具有相同 ID 的新通知,并将自动取消设置为 true

标签: android service notifications android-notifications


【解决方案1】:

正如@orium 所建议的那样,要解决此问题,您需要在前台模式下停止服务以删除通知,并使用相同的 ID 创建一个新通知,但将设置设置为可关闭。 那将是: 停止前景(真) 并使用 setAutoCancel(true) 创建通知

【讨论】:

    【解决方案2】:

    不需要删除通知。您可以使用以下方法将其与服务分离:

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
        stopForeground(STOP_FOREGROUND_DETACH);
    else
        stopForeground(false);
    

    如果您需要更新任何信息,您可以使用通知管理器再次使用相同的 ID 进行通知。 STOP_FOREGROUND_DETACH 标志将防止通知在以后的 Android 版本中销毁服务时消失。您不会像关闭第一个通知后那样看到通知消失和重新出现。

    【讨论】:

    • STOP_FOREGROUND_DETACH 仅在 API >= 24 中可用。
    【解决方案3】:

    您可以为通知使用 0 的通知 ID,在这种情况下,将调用通知的删除挂起意图,您可以在其中停止服务。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-16
      相关资源
      最近更新 更多