Search code examples
androidandroid-intentnotificationsandroid-pendingintent

Android Notification not closing on AddAction click


I used some answers I found here on Stack Overflow, but they did not work. But basicaly, I need my notification to do two things. One, I need it to open the app again when the notification itself is clicked, and I need it to close out the notification when the AddAction is clicked.

The notification opens the app when it is clicked, and this is correct, but when I click the AddAction ("done"), it does the same thing. Instead of the action closing the notification, it opens up the app just as with the notification itself. What could be going wrong?

public void onInput(MaterialDialog dialog, CharSequence input) {

    //notification body
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext());
        PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0,
            new Intent(getApplicationContext(), MainActivity.class)
                    .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP),
            0);

        //Rest of Notification
        builder.setStyle(new NotificationCompat.BigTextStyle().bigText(input.toString())); //BigText
        builder.setOngoing(true); //Make persistent
        builder.setContentIntent(pendingIntent); //OnClick for Reopening App
        builder.setSmallIcon(R.drawable.ic_note);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        builder.setContentTitle("Remember!");
        builder.setContentText(input.toString()); //Get text from dialog input
        Intent closeIntent = new Intent(getApplicationContext(), MainActivity.class);
        closeIntent.putExtra(getPackageName(), NOTIFICATION_ID);
        PendingIntent closeBtn = PendingIntent.getActivity(getApplicationContext(), 0, closeIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.addAction(R.drawable.ic_action_name, "Done", closeBtn); //Action for the closer
        notificationManager.notify(NOTIFICATION_ID, builder.build());

    //toast
    Toast.makeText(MainActivity.this, "Done! Reminder has been set. Check your Notification Bar! :)",
            Toast.LENGTH_LONG).show();

    //Close app when done entering in text
    finish();
}

Solution

  • simply add builder.autoCancel(true);

    This will solve your problem.