startActivityForResult with three activities

2019-09-15 09:26发布

问题:

I have three activities, let's just call them Activity A, Activity B and Activity C

At first I'm at the Activity A and I'm starting a QR scanner (Activity B) with startActivityForResult like this:

Intent i;
i = new Intent(this, QrActivity.class);
startActivityForResult(i, 1);

Once the Activity B opens, this is the code for handling result and returning to previous activity:

 public void handleDecode(Result rawResult, Bitmap barcode) 
{

    if (rawResult != null) {
        String textResult = rawResult.getText();

        if (textResult != null) {
            Intent returnIntent = new Intent();
            returnIntent.putExtra("result", textResult);
            setResult(RESULT_OK,returnIntent);     
            finish();       
        }
//rest of the code

Now this works completely fine, once the Activity A is opened again everything works as it should. It goes like this: A --> B --> A

The problem appears when I try to go like this: A --> C --> B --> A

The user has two options, either to start the Activity B (qr scanner) from Activity A or from Activity C. I always want to handle Activity B result with Activity A even if the user accessed Activity B from Activity C.

Once I open the Activity B (qr scanner) from activity C, this is how I tried to solve it:

I called finish() on Activity C when Activity B is called:

Intent in;
in = new Intent(this, QrActivity.class);
startActivityForResult(in, 1);
finish();

And in Activity B, instead of

Intent returnIntent = new Intent();

I'm setting intent as:

Intent returnIntent = new Intent(QrActivity.this, CheckpointsActivity.class);

And after it goes back to activity A nothing happens, like the Activity B was never even opened, it doesn't seem to get the result when Activity B is started from Activity C.

Any kind of help will be greatly appreciated! I know this is all very confusing but I can add any more detail if you want.

回答1:

This is not how startActivityForResult() is meant to work. You would be better off saving the data in SharedPreferences or somewhere else.

You also could probably use startActivityForResult() to start ActivityC from A then do the same to start B from C (don't finish C yet), passing back the result you want to pass to A. So it would be something like

A --> C --> B (finish) --> C (finish) --> A

using startActivityForResult() to start C and B and returning a result with setResult() to the onActivityResult() of both C and A