staddle
staddle

Reputation: 380

How to create a notification only on start of an app?

I want to create a notification only when I first start the app. Then the notification is persistent, so if I click on it, it starts the app, but doesn't disappear.

But because I create my notification in the onCreate() of my activity, everytime I click on the notification, it creates a new notification.

How can I prevent this? Is there a way to check if a current notification is running?

@Override
    protected void onCreate(Bundle savedInstanceState) {    
Notification.Builder mBuilder =
                new Notification.Builder(this)
                        .setSmallIcon(R.drawable.not_norm_icon)
                        .setContentTitle("test")
                        .setContentText("test");

        Intent resultIntent = new Intent(this,MainActivity.class);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); 
        stackBuilder.addParentStack(MainActivity.class);
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent =
                stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(resultPendingIntent);
        Notification n = mBuilder.build();
        n.flags |= Notification.FLAG_NO_CLEAR;


        if (mNotificationManager != null) {
            mNotificationManager.notify(mNotificationId, n);
        }}

Upvotes: 1

Views: 62

Answers (1)

Suraj Nair
Suraj Nair

Reputation: 1847

You can clear notification on click by adding this line

mBuilder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL;

Upvotes: 1

Related Questions