Saturday, August 14, 2010

Android Intents

In extending an application to multiple Activities, one realizes that the Android environment is like a mini-MOM (Message Oriented Middleware) setup. Activities can message and transport data (explicitly or implicitly) between each other by the use of Intent functions.

The simplest example of data passing is one where data is returned from a sub-activity to its caller. To return data from a sub-activity to it's caller, on finishing it can do something like:

Intent i = new Intent(this, Caller.class); // note the use of Caller.class
i.putExtra("returnKey","Sub-Activity Data"); // a named piece of data
setResult(RESULT_OK, i);
finish();

The caller then get's the data (in a loosely coupled way) with:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
super.onActivityResult(requestCode, resultCode, intent);
Bundle extras = intent.getExtras();
System.out.println(extras != null ? extras.getString("returnKey"):"nothing returned");
}

What's interesting and unintuitive about this is the sub-activity's instantiation of a new Intent with the caller's class to set the data. Would have assumed instead that the caller's Intent object be somehow retrieved from it's sub-activity. Of course in other cases the messaging is between activities that do not have a calling rapport.

The official Intent examples are here.