Search code examples
androidstart-activity

Code flow using startActivityForResult()


I'm working on an Android app. I have an Activity that checks to see if an XML file exists on my device. If it doesn't exist, I call a routine that does a bunch of stuff, including downloading that file from a URL.

If it does exist, I want to prompt (Yes/No) the user to see if they want to re-download the file, or just skip it.

I started by using a Dialog. The discussions I saw said that Dialogs are only asynchronous, so I switched to using an Activity to prompt for Yes/No.

After further reading, I believe the real answer is that starting an Activity using startActivity() sets off the Activity asynchronously, but using startActivityForResult() sets it off synchronously (blocking). Is this statement correct?

OK, assuming my statement above is correct, I have been looking into how to get back to my original starting point in the code flow, knowing which button (Yes/No) was selected by the user.

All of the examples show me that I need to get my result using this.

protected void onActivityResult(int requestCode, int resultCode,Intent data) {

}

I am struggling with how to put this into my code so that it flows easier. I see plenty of examples that show the pieces of code needed, but I'm not clear on how it all fits together. Does my code structure end up like this:

public class MainScreen extends Activity    {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    protected void onButtonClick(parameters)    {
        /* Do some work to see if the file exists */
        if (!file.exists()) {
            runComplexRoutine(various_parameters);

        } else {
            Intent myIntent = new Intent(getBaseContext(), PromptingActivity.class);
            myIntent.putExtra("filename", variable_holding_filename);   // Just passing a parameter to use in the title of the caled Activity
            startActivityForResult(myIntent, 1);
                        // Point A
        }
    }


    protected void onActivityResult(int requestCode, int resultCode,Intent data) {
        if (resultsCode == Activity.RESULT_OK)  {
            runComplexRoutine(various_parameters);
        }
        // else, do nothing...
    }

}

My problem with this is that I have to pass lots of various_parameters around. It would be great if I could resume flow at Point A, but that doesn't seem possible. Am I correct here?


Solution

  • startActivityForResult() is asynchronous. It can feel synchronous to the user since the UI will change and your calling activity will be paused (your onPause() method will be called).

    Your calling activity however is still able to run code; you'll implement a callback to be called when the activity you started for result is completed (which makes it quite like a dialog).