Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing an entry from an Bundle (i.e. extras) doesn't seem to work in combination with the back button

I have a BroadcastReceiver that listen to incoming SMS'. If the message is from a certain sender, the BroadcastReceiver starts my app with the following code:

final Intent activityIntent = new Intent(context, MainActivity.class);
activityIntent.putExtra("smsChallenge", smsText);
activityIntent.putExtra("smsSenderNumber", senderMobilNumber);
activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(activityIntent);

In the MainActivity of my app (i.e. in onCreate()), I extract the value smsChallenge out of the intent and DELETE IT AFTER THE EXTRACTION with the following code:

Bundle extras = getIntent().getExtras();
if (extras != null) {
    smsChallenge = extras.getString("smsChallenge");
    extras.remove("smsChallenge");
}

So my app gets started from the SMS and runs fine... But if I choose to press the BACK button and restart the application (i.e. through the Taskmanager), the value smsChallenge is still in the bundle extras. This means, my restarted app thinks that it is re-started because of a new SMS which is not true...

Any ideas why removing the key-value from the bundle doesn't seem to work when using the BACK button and restarting the app again?

like image 544
pfust75 Avatar asked Apr 04 '12 16:04

pfust75


2 Answers

Because getExtras() creates a copy of intent extras.

You have to do like this

getIntent().removeExtra("smsChallenge");

Docs : http://developer.android.com/reference/android/content/Intent.html#removeExtra(java.lang.String)

like image 192
Ajay S Avatar answered Sep 20 '22 09:09

Ajay S


I think that you can not fix this behavior because by the time you get access to the intent, the os would have already saved the intent for later launch via recent apps.

  1. You can either add a flag to remove from recent apps, but in that way the app will not appear in the recent apps.
  2. Add in persistent storage the last sms that was handled in your MainActivity and do this check in your onCreate, discarding an intent for an sms that was already handled.
  3. A final solution would be not to send the data in the intent at all. For example, save them in a "pending" persistent storage. When your MainActivity starts, let it check for pending stuff, and clear this pending item.

Persistent storage could be SharedPreferences for example.

I would advise you to use 2 but you should count the sms received and use that counter as an id for the sms. Do not rely on the sms content and sender as an identifier for the sms.

like image 25
Sherif elKhatib Avatar answered Sep 22 '22 09:09

Sherif elKhatib