Home » Android » android – Can't remove intent extra!

android – Can't remove intent extra!

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m creating a notification for the notification tray. I’m specifying a click intent like this:

Intent intent = new Intent(context, MyActivity.class);
intent.putExtra("foo", true);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.setData(Uri.parse("" + System.currentTimeMillis()));

The MyActivity class gets launched just fine with the “foo” parameter present. However, I cannot get rid of that extra afterwards – it seems to persist in the Intent:

// MyActivity
public void onNewIntent(Intent intent) {
    super.onNewIntent(intent);

    // please go away..
    intent.removeExtra("foo");
    getIntent().removeExtra("foo");
}

Iterating over the keys of the intent shows that “foo” no longer exists. But if I background the activity, then bring it to the foreground again, the “foo” parameter is present again.

Anyone know how to really get rid of it? I’ve also tried calling setIntent(), same behavior. It’s like the launcher holds onto the original intent and keeps reusing it.

Thanks

How to&Answers:

That is exactly what Android is doing. Modifying the intent parameter within the onNewIntent method has no effect on the notification system’s stored intent. You should create a new Intent and store that locally in your activity, saving and restoring it like any other data.

EDIT: If you don’t need to reuse the intent itself, it would probably make more sense to store the relevant data separately.