This is a mirror of official site: http://jasper-net.blogspot.com/

Communicating between running activities

| Tuesday, April 12, 2011
SDK Version:  M3
Starting a new activity from another and passing some data to it is a simple and basic thing in android. But if you want an already running activity to come to foreground, and pass data to it, it can be a bit tricky.

First of all by default if you call an activity with an intent, a new istance of that activity will be created and displayed, even if another instance is already running. To avoid this the activity must be flagged that, it should not be instantiated multiple times. To achieve this we will set the launchMode of the activity to singleTask in the AndroidManifest.xml

<activity android:name="Activity1" android:launchMode="singleTask" android:label="@string/app_name">

This way when we call this activity using an intent, if there is an existing instance, the system will route the request to it. Hoever the onCreate method, where we usually process the passed extraData, will not run this time.

As its name shows it runs when the activity is created and this time it already exists, so the method called onNewIntent() will be called.

protected void onNewIntent(Intent intent) {
  super.onNewIntent(intent);
  setIntent(intent);//must store the new intent unless getIntent() will return the old one
  processExtraData();
}

Do not forget that we can receive data in the normal way in onCreate, when the activity is first created, and since the system can easily kill activities in the backround, if this happens, the onCreate method will be called instead of onNewIntent.

Read more: Hello android

Posted via email from Jasper-net

0 comments: