How to manage `startActivityForResult` on Android?
In my activity, I'm calling a second activity from the main activity by startActivityForResult
. In my second activity there are some methods that finish this activity (maybe without result), however, just one of them return a result.
For example, from the main activity I call a second one. In this activity I'm checking some features of handset such as does it have a camera. If it doesn't have then I'll close this activity. Also, during preparation of MediaRecorder
or MediaPlayer
if a problem happens then I'll close this activity.
If its device has a camera and recording is done completely, then after recording a video if a user clicks on the done button then I'll send the result (address of the recorded video) back to main activity.
How do I check the result from the main activity?
From your FirstActivity
call the SecondActivity
using startActivityForResult()
method
For example:
Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);
In your SecondActivity
set the data which you want to return back to FirstActivity
. If you don't want to return back, don't set any.
For example: In secondActivity if you want to send back data:
Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(Activity.RESULT_OK,returnIntent);
finish();
If you don't want to return data:
Intent returnIntent = new Intent();
setResult(Activity.RESULT_CANCELED, returnIntent);
finish();
Now in your FirstActivity class write following code for the onActivityResult()
method.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
String result=data.getStringExtra("result");
}
if (resultCode == Activity.RESULT_CANCELED) {
//Write your code if there's no result
}
}
}//onActivityResult
How to check the result from the main activity?
You need to override Activity.onActivityResult()
then check its parameters:
requestCode
identifies which app returned these results. This is defined by you when you call startActivityForResult()
. resultCode
informs you whether this app succeeded, failed, or something different data
holds any information returned by this app. This may be null
. Complementing the answer from @Nishant,the best way to return the activity result is:
Intent returnIntent = getIntent();
returnIntent.putExtra("result",result);
setResult(RESULT_OK,returnIntent);
finish();
I was having problem with
new Intent();
Then I found out that the correct way is using
getIntent();
to get the current intent
链接地址: http://www.djcxy.com/p/26212.html上一篇: AsyncTask不是通用的?