Temitayo
Temitayo

Reputation: 812

Android: Intent Extras not passed with startActivity() outside Activity context

I have a class that listens to SMS broadcast and, it then open an activity in the same application to display the message. This is part of a larger project.

Since the broadcast class does not extend the activity class, calling an Activity with intent requires that I flag it with Intent.FLAG_ACTIVITY_NEW_TASK.

Now the Intent has an extra (the SMS message and some parameters as a single string) which i want to send with the intent. All went well but the Extras are not sent with the intent.

Here are my code From the broadcast class

//After getting the message into String S and doing some process
Intent inte = new Intent(context.getApplicationContext(), StartApp.class);
inte.putExtra("messageAsString", S.toString()); //Where S is declared somewhere
inte.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(inte);

From the activity recieving the Intent in the onCreate() method

if(getIntent().hasExtra("messageAsString")) {
        String message = getIntent().getStringExtra("messageAsString").toString();
        Toast toast = Toast.makeText(this, "Received SMS: " + message , Toast.LENGTH_LONG);
        toast.show();
}

The application may have already running, the home button has been pressed. Either way, what I want to achieve is that as the registered reciever receives the message, I want to start an activity automatically and pass the message and its meta data to it.

I know I'm missing something somewhere but will appreciate your swift help

Upvotes: 1

Views: 2243

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006734

You also need to handle onNewIntent(), which may be called if the activity already exists and startActivity() brings an existing instance back to the foreground. Your extra is probably in there.

Upvotes: 5

Related Questions