user2218845
user2218845

Reputation: 1121

How to cancel current activity during the creation of the same one?

There is the following code:

    Intent i = new Intent(this, MessagesActivity.class);
    PendingIntent pi = PendingIntent.getActivity(this, 100, i, PendingIntent.FLAG_CANCEL_CURRENT);
    NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

    NotificationCompat.Builder nb = new NotificationCompat.Builder(this);
    nb.setContentText("There is a new message for you").setContentTitle("New message").setContentIntent(pi);
    nb.setWhen(System.currentTimeMillis()).setDefaults(Notification.DEFAULT_ALL);
    nb.setTicker("SomeText").setSmallIcon(android.R.drawable.ic_dialog_alert);
    manager.notify(100, nb.getNotification());

When user clicks by some notification created with this code the app should open MessagesActivity activity. It works. But if user is in MessagesActivity already this code executes a new copy of MessagesActivity. How can I fix it? Thanks in advance.

Upvotes: 0

Views: 139

Answers (2)

midhunhk
midhunhk

Reputation: 5554

Can you try this for your activity in the manifest file?

Add launchMode="singleTop" as a property for your activity.

Android Developers

Upvotes: 1

Armaan Stranger
Armaan Stranger

Reputation: 3130

Try using:

FLAG_ACTIVITY_NO_HISTORY flag for your intent.

Intent i = new Intent(this, MessagesActivity.class).setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

it will not make activity in history stack. so there will be not more than one instance.

Upvotes: 1

Related Questions