This example shows how an Activity accepts the results returned by another Activity opened through it.
A common example is that when sending a text message, you need to open the contact program to select a contact, and then return the selected information to the sender program.
The setResult () method is used to send information, and the onActivityResult () method is used to receive information.
// Definition of the one requestCode we use for processing ing resuls.
Static final private int GET_CODE = 0;
Private OnClickListener mGetListener = new OnClickListener (){
Public void onClick (View v ){
// Start the activity whose result we want to retrieve.
// Result will come back with request code GET_CODE.
Intent intent = new Intent (ReceiveResult. this, SendResult. class );
StartActivityForResult (intent, GET_CODE );
}
};
The startActivityForResult method starts the Activity from which we want to obtain information. GET_CODE returns the returned results together when the information is returned, so that the returned results are obtained through GET_CODE.
Www.2cto.com
In SendResult. java:
Private OnClickListener mCorkyListener = new OnClickListener ()
{
Public void onClick (View v)
{
// To send a result, simply call setResult () before your
// Activity is finished.
SetResult (RESULT_ OK, (new Intent (). setAction ("Corky! "));
Finish ();
}
};
Private OnClickListener mviletlistener = new OnClickListener ()
{
Public void onClick (View v)
{
// To send a result, simply call setResult () before your
// Activity is finished.
SetResult (RESULT_ OK, (new Intent (). setAction ("Violet! "));
Finish ();
}
};
Call the setResult method to return the result before the program stops.
@ Override
Protected void onActivityResult (int requestCode, int resultCode,
Intent data ){
// You can use the requestCode to select between multiple child
// Activities you may have started. Here there is only one thing
// We launch.
If (requestCode = GET_CODE ){
// We will be adding to our text.
Editable text = (Editable) mResults. getText ();
// This is a standard resultCode that is sent back if
// Activity doesn' t supply an explicit result. It will also
// Be returned if the activity failed to launch.
If (resultCode = RESULT_CANCELED ){
Text. append ("(canceled )");
// Our protocol with the sending activity is that it will send
// Text in 'data' as its result.
} Else {
Text. append ("(okay ");
Text. append (Integer. toString (resultCode ));
Text. append (")");
If (data! = Null ){
Text. append (data. getAction ());
}
}
Text. append ("\ n ");
}
}
The onActivityResult method accepts the returned results and runs them before the onResume method. The three parameters mean:
1. requestCode is the second parameter in startActivityForResult. It can be used to identify which activity sends the request.
2. resultCode is the code returned by the sub-activity, generally RESULT_ OK and RESULT_CANCELLED.
3. data is the returned result data.