滑动关闭服务通知

4

我原以为这不是问题,但还是遇到了麻烦。 无论我怎么做,我的服务通知都无法滑动消除。

我有一个进度通知,在服务中使用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) - 通知将被正确地移除。

有人有什么想法吗?我在这里做错了什么?


1
在调用stopForeground(true)之后,试图通过创建一个新的通知选项setCancelable(true)并使用相同的通知ID来更新通知。 - orium
NotificationCompat.Builder没有“setCancelable”方法。 - AAverin
你有将 setAutoCancel 设置为 通知而不是旧的吗? - orium
当然可以。但它仍然不能按预期工作。 - AAverin
1
这是我实现的方式:我调用了stopForeground(true)来取消前台服务,然后使用mNotificationManager.cancel(NOTIFICATION_ID)取消通知,最后使用相同的ID显示新通知,并将autocancel设置为true。 - orium
显示剩余2条评论
3个回答

4

正如@orium所建议的,要解决这个问题,您需要停止前台模式下的服务,删除通知,并使用相同的ID创建一个新的通知,但将设置设置为可解除。 操作步骤如下: stopForegound(true) 并创建具有setAutoCancel(true)的通知


1

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

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。 - shubham vashisht

0

您可以使用通知 ID 为 0 的通知,这样通知的删除待定意图将被调用,您可以在其中停止服务。


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