setAutoCancel() 在 API 26 中不起作用

setAutoCancel() not working in API 26

我想使用 android oreo 通过点击或滑动来关闭通知 setAutoCancel(true)无效。

所以这是我的代码:

public class AlarmService extends Service {


private NotificationManager mManager;
.
.
.

@SuppressLint("ClickableViewAccessibility")
@Override
public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);


    ////////////////////////////////////////////////////////////////////////////////////////////////////////
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

        String CHANNEL_ID = getString(R.string.app_name);
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, getString(R.string.app_name), NotificationManager.IMPORTANCE_DEFAULT);
        ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);

        Intent intent1 = new Intent(this.getApplicationContext(), MainActivity.class);
        intent1.putExtra("code", 1);
        intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingNotificationIntent = PendingIntent.getActivity(this.getApplicationContext(), 2, intent1, PendingIntent.FLAG_CANCEL_CURRENT);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);


        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("title")
                .setSmallIcon(R.drawable.logo)
                .setContentIntent(pendingNotificationIntent)
                .setNumber(1)
                .setSound(defaultSoundUri)
                .setContentText("more")
                .setAutoCancel(true).build();

        notification.flags |= Notification.FLAG_AUTO_CANCEL;

        startForeground(2, notification);


    } 

谢谢。

当服务仍在前台时,AutoCancel 不起作用。 尝试从前台删除服务:

startForeground(2, notification);
stopForeground(false); //false - do not remove generated notification