Search code examples
javaandroidalarmmanagerandroid-notificationsandroid-8.0-oreo

setAutoCancel() not working in API 26


I would to dismiss notification by click or swipe using android oreo setAutoCancel(true)is not working.

so here is my code:

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);


    } 

Thanks.


Solution

  • AutoCancel does not work when service is still on foreground. Try remove service from foreground:

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