Android 刷卡取消服务通知

Android 刷卡取消服务通知,android,service,notifications,android-notifications,Android,Service,Notifications,Android Notifications,我想这根本不是问题,但仍然是。 无论我做什么,我的服务通知都不想刷消 我有一个进度通知,它是使用startForeground(id,notification)在服务中启动的。 以下是我如何构建它: public Notification createErrorNotification(String message) { NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationCo

我想这根本不是问题,但仍然是。 无论我做什么,我的服务通知都不想刷消

我有一个进度通知,它是使用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)-通知已正确删除


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

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

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

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

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

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

在call stopForeground(true)之后,尝试更新通知,通过使用选项setCanceble(true)和相同的通知id创建一个新通知,您在我的代码段中可以看到NotificationCompat.BuilderAs没有“setCancelable”方法,autoCancel是否已设置您是否已将setAutoCancel设置为新通知,而不是旧通知?我是如何执行此操作的:我调用stopForeground(true),取消通知mNotificationManager.cancel(通知\u ID),然后显示具有相同ID的新通知,并且autoCancel设置为trueSTOP\u FOREGROUND\u DETACH仅在API>=24中可用。