startActivityForResult

与startActivityForResult相关的函数有两个,分别是onActivityResult和setResult。

(1)如果想在Activity中得到新打开Activity关闭后返回的数据,需要使用系统提供的startActivityForResult(Intentintent, int requestCode)方法打开新的Activity,新的Activity关闭后会向前面的Activity传回数据,为了得到传回的数据,必须在前面的Activity中重写onActivityResult(int requestCode, int resultCode, Intent data)方法。

(2)新Activity关闭前需要向前面的Activity返回数据,需要使用系统提供的setResult(intresultCode, Intent data)方法实现。

(3)请求码requestCode的作用:用于标识请求的来源。

(4)结果码resultCode的作用:用于标识返回的数据来自于哪个新的Activity。


android官网解释

Starting Activities and Getting Results

   The startActivity(Intent) method is used to start a new activity, whichwill be placed at the top of the activity stack. It takes a single argument, anIntent, which describes the activity to be executed.

   Sometimes you want to geta result back from an activity when it ends. For example, you may startan activity that lets the user pick a person in a list of contacts; when itends, it returns the person that was selected. To do this, you call thestartActivityForResult(Intent, int) version with a second integer parameter identifying the call. Theresult will come back through your onActivityResult(int, int, Intent) method.

    When an activity exits, it can callsetResult(int) to return data back to its parent. It must always supply aresult code, which can be the standard results RESULT_CANCELED, RESULT_OK, orany custom values starting at RESULT_FIRST_USER. In addition, it can optionallyreturn back an Intent containing any additional data it wants. All of thisinformation appears back on the parent's Activity.onActivityResult(), alongwith the integer identifier it originally supplied.

   If a child activity fails for any reason (such as crashing), the parentactivity will receive a result with the code RESULT_CANCELED.


你可能感兴趣的:(startActivityForResult)