Search code examples
androidcordovanotificationsstatusbar

Close status bar when button notification is clicked


How can I close status bar after notification button click?

I tried this, but I had an exception:

java.lang.NoSuchMethodException: collapse []
   at java.lang.Class.getConstructorOrMethod(Class.java:460)
   at java.lang.Class.getMethod(Class.java:915)
   ...

My code:

NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
    .setSmallIcon(R.drawable.icon)
    .setContentTitle("Sync Failed")
    .setContentText("Lorem ipsum dolor sit amet")
    .setStyle(new NotificationCompat.BigTextStyle().bigText("Lorem ipsum dolor sit amet"))
    .addAction(R.drawable.change, "Change Pass", pChangePass)
    .addAction(R.drawable.remove, "Ignore", pIgnore)
    .setAutoCancel(false);
mNotificationManager.notify(accountUnique, builder.build());

At NotificationIntent class

@Override
public void onReceive(Context context, Intent intent) {
    int notificationID = intent.getExtras().getInt("NOT_ID");
    this.callbackContext = StatusBarNotification.getCallback();
    this.mNotificationManager = StatusBarNotification.getNotificationManager();

    this.mNotificationManager.cancel(notificationID);
    this.callbackContext.success(returnJSON(intent));
}

Solution

  • Ok, I solved it.

    private int currentApiVersion = android.os.Build.VERSION.SDK_INT;
    ...
    
    Object sbservice = context.getSystemService("statusbar");
    try {
        Class<?> statusbarManager = Class.forName("android.app.StatusBarManager");
        if (currentApiVersion <= 16) {
            Method collapse = statusbarManager.getMethod("collapse");
            collapse.invoke(sbservice);
        } else {
            Method collapse2 = statusbarManager.getMethod("collapsePanels");
            collapse2.invoke(sbservice);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }