How to remove notifications when touched?

291 Views Asked by At

I am trying to develop an app that will make notifications when you exit. But I want that when you touch the notification and you reopen the application, the notification disappears. How i can do it?

My code:

public class MainActivity extends Activity {

    NotificationCompat.Builder mBuilder;

    @SuppressWarnings("deprecation")    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main_land);
        this.setVolumeControlStream(AudioManager.STREAM_MUSIC);


        mBuilder =
                new NotificationCompat.Builder(MainActivity.this)
                    .setSmallIcon(android.R.drawable.stat_sys_warning)
                    .setContentTitle("Mensaje de Alerta")
                    .setContentText("Ejemplo de notificación.")
                    .setContentInfo("4")
                    .setTicker("Alerta!");

        }


    public void salir(View view) {

        finish();
        Intent notIntent =
                new Intent(MainActivity.this, MainActivity.class);

            PendingIntent contIntent =
                PendingIntent.getActivity(
                    MainActivity.this, 0, notIntent, 0);

            mBuilder.setContentIntent(contIntent);
            NotificationManager mNotificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

                mNotificationManager.notify("NOTIFICATION", 0, mBuilder.build());

    }

}

This code only makes the Notification and it opens the app again.

1

There are 1 best solutions below

2
On BEST ANSWER

Using flags

 notification.flags = Notification.FLAG_AUTO_CANCEL;

Using Notification builder

NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setAutoCancel(true);

Using Notification Manager

notificationManager.cancel(NOTIFICATION_ID);

for API level 18 and above

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public class MyNotificationListenerService extends NotificationListenerService {...}
...

private void clearNotificationExample(StatusBarNotification sbn) {
    myNotificationListenerService.cancelNotification(sbn.getPackageName(), sbn.getTag(), sbn.getId());
}