startActivityForResult method is a method in android activity starts, this method takes two parameters, the first one is the Intent, the other is a request code, the request code is a unique value can be long.
This method can be destroyed after the event, it returns a result to the previous activity.
For example: A opened the event activity B, then B activity after the destruction, you can return a result to the activities A.
This time is necessary in the event A, the method used to open the activity startActivityForResult B
button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent("com.example.activitytest.ACTTON_START"); startActivityForResult(intent,1);//打开活动B } });
In the results of the activity by the method B setResult set to return, setResult () accepts two parameters, the first one is active to return the processing result, and generally only used RESULT_OK RESULT_CANCELED, other data which is transmitted with the Intent to back .
button2.setOnClickListener ( new new View.OnClickListener () { @Override public void the onClick (View View) { the Intent Intent = new new the Intent (); intent.putExtra ( "data_return", "test"); // results to return setResult (RESULT_OK, Intent); Finish (); // destruction activity B } });
B is destroyed after the event, will be on a callback activity (ie activity A) of onActivityResult () method (in the event you want to get passed in the A result, we need to override this method).
@Override // 请求码 处理结果 带返回数据的Intent protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { switch (requestCode){ case 1 : if(resultCode == RESULT_OK){ String returnData = data.getStringExtra("data_return"); Log.d("MainActivity",returnData); } break; default: } }
So after the event B is destroyed, it will return to activities A, B data activity to get a return. However, if the user does not click on the activities defined in the B button button2, but press the Back button, this time also need to override onBackPressed activity of B () method.
@Override public void onBackPressed() { Intent intent = new Intent(); intent.putExtra("data_return","测试一下"); setResult(RESULT_OK,intent); finish(); } });