0

For various reasons, my app creates entries in the notification bar. When the user clicks on the notification, I want to display a custom activity that presents the entry in a certain format.

Intent intent = new Intent(applicationContext, TextMessageViewerActivity.class);
intent.putExtra("text_message", someText);
PendingIntent contentIntent = PendingIntent.getActivity(applicationContext, 0, intent, 0);
// now create a notification and post it. no fancy flags

It all boils down to sending a string via an Intent extra, and displaying that in my Activity. What happens is that the first Intent that gets delivered to my Activity gets "stuck" somehow, and all further Intents delivered to it display the only the first Intent's extra.

public class TextMessageViewerActivity extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.text_viewer);
    }

    @Override
    public void onResume()
    {
        super.onResume();

        Intent startingIntent = getIntent();
        String message = startingIntent.getStringExtra("text_message");
        String displayMessage = message != null ? message : "No message found";

        ((TextView)findViewById(R.id.text_viewer_text_id)).setText(displayMessage);
    }
}

What am I not understanding about the Android Activity lifecycle?

WorkerThread
  • 2,195
  • 2
  • 19
  • 23

2 Answers2

2

I learned something new today: PendingIntent.getActivity may return the same PendingIntent for a given Activity. In order to create a unique PendingIntent for each unique Intent to send, you must specify the PendingIntent.FLAG_ONE_SHOT flag when creating it.

So for example, the PendingIntent creation line in my code above should have been:

PendingIntent contentIntent = PendingIntent.getActivity(applicationContext, 0, intent, PendingIntent.FLAG_ONE_SHOT);
WorkerThread
  • 2,195
  • 2
  • 19
  • 23
0

I think you need to use the onNewIntent() function. It changes the intent that your Activity sees. Usage:

/**
  * onResume is called immediately after this.
  */
@Override
protected void onNewIntent(Intent intent) {
    setIntent(intent);
    resolveIntent(intent);
}

Here resolveIntent is used to actually deal with the new incoming intent. Look at documentation here.

Cubic
  • 358
  • 1
  • 3
  • 9
  • That's actually what I thought at first, but onNewIntent is not called unless you specify "singleTop" for your activity. It's the intuitive answer, though. – WorkerThread Apr 11 '11 at 22:55