I'm trying to implement a notification with 2 actions added and let it be cancelled once one of the actions is called but this doesn't happen. Setting autoCancel and contentIntent make the notification disappear only when clicking the text instead of the actions. Here's my code
package com.example.notificationtest;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
public class OtherNotifications extends AppCompatActivity {
public static String CHANNEL_ID;
public static int REQUEST_CODE_NOTIFICATION_PAGE;
public static int REQUEST_CODE_HOME_PAGE;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_other_notifications);
CHANNEL_ID = getResources().getString(R.string.basicChannelID);
REQUEST_CODE_NOTIFICATION_PAGE = Integer.parseInt(getResources().getString(R.string.requestCodeNotificationPage));
REQUEST_CODE_HOME_PAGE = Integer.parseInt(getResources().getString(R.string.requestCodeHomePage));
//BACK BUTTON
Button btnBack = findViewById(R.id.btnBack);
btnBack.setOnClickListener(v -> onBackPressed() );
Button btnNotificationButton = findViewById(R.id.btnNotificationButton);
btnNotificationButton.setOnClickListener(v -> {
NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
//NotificationManagerCompat nmc = NotificationManagerCompat.from(this);
Intent iNotificationPage = new Intent(this, OtherNotifications.class);
PendingIntent piNotificationPage = PendingIntent.getActivity(
OtherNotifications.this,
REQUEST_CODE_NOTIFICATION_PAGE,
iNotificationPage,
PendingIntent.FLAG_IMMUTABLE);
Intent iHomePage = new Intent(this, MainActivity.class);
PendingIntent piHomePage = PendingIntent.getActivity(
OtherNotifications.this,
REQUEST_CODE_HOME_PAGE,
iHomePage,
PendingIntent.FLAG_IMMUTABLE);
NotificationCompat.Builder nb = new NotificationCompat.Builder(OtherNotifications.this, CHANNEL_ID);
nb.setContentTitle("Notification with button").
setContentText("Press the button").
setSmallIcon(R.drawable.ic_launcher_background).
addAction(R.drawable.ic_launcher_background, "Back to Notifications page", piNotificationPage).`your text`
addAction(R.drawable.ic_launcher_background, "Back to Home Page", piHomePage).
setAutoCancel(true).
setContentIntent(PendingIntent.getActivity(this, 0, new Intent(), 0));
nm.notify(3, nb.build());
});
}
}
I tried setting setAutoCancel, setContentIntent and setOngoing but i managed to get the notification disappear only when clicking the text of the notification (as it would do normally without actions)