How to manage startActivityForResult on Android?

2018-12-30 22:59发布

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?

8条回答
长期被迫恋爱
2楼-- · 2018-12-30 23:35

First you use startActivityForResult() with parameters in first Activity and if you want to send data from second Activity to first Activity then pass value using Intent with setResult() method and get that data inside onActivityResult() method in first Activity.

查看更多
路过你的时光
3楼-- · 2018-12-30 23:37

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
查看更多
登录 后发表回答