android: makes activity A wait for activity B to finish and returns some values

后端 未结 1 1541
南方客
南方客 2020-12-29 12:39

I have a program that needs to...

  1. In Activity A, do some jobs
  2. Start up Activity B (a WebView), let user fills i
相关标签:
1条回答
  • 2020-12-29 13:31

    The simple answer is there is no other way. This is how it's mean to be done in Android. The only thing, I believe, you're missing is passing a request code to activity B. Without it, you wouldn't be able to differentiate which other activity returned result to activity A.

    If you're invoking different activities from your A, use different requestCode parameter when starting activity. Furthermore, you can pass any data back to activity B using the same Intent approach (ok, almost any):

    public final static int REQUEST_CODE_B = 1;
    public final static int REQUEST_CODE_C = 2;
    ...
    
    Intent i = new Intent(this, ActivityB.class);
    i.putExtra(...);    //if you need to pass parameters
    startActivityForResult(i, REQUEST_CODE_B);
    
    ...
    
    //and in another place:
    Intent i = new Intent(this, ActivityC.class);
    i.putExtra(...);    //if you need to pass parameters
    startActivityForResult(i, REQUEST_CODE_C);
    

    Then in your on ActivityResult:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch(requestCode) {
            case REQUEST_CODE_B:
                //you just got back from activity B - deal with resultCode
                //use data.getExtra(...) to retrieve the returned data
                break;
            case REQUEST_CODE_C:
                //you just got back from activity C - deal with resultCode
                break;
        }
    }
    

    OnActivityResult is executed on the GUI thread, therefore you can make any updates you want straight in here.

    Finally, in Activity B, you'd have:

    Intent resultIntent = new Intent();
    resultIntent.putExtra(...);  // put data that you want returned to activity A
    setResult(Activity.RESULT_OK, resultIntent);
    finish();
    

    I'm not sure why you need AsyncTask to handle results.

    0 讨论(0)
提交回复
热议问题