Check If Activity Has Been Called for Result
Asked Answered
P

2

89

Is it possible to know if some activity has been called for result, using startActivityForResult() or if was only started using startActivity()?

I need to control this, if its called for result the behaviour will be different.

Polash answered 25/5, 2013 at 20:34 Comment(0)
H
182

When your activity was started just by startActivity() a getCallingActivity() method in target activity will return null.

When it was called by startActivityForResult() it will return name of calling activity.

See Docs for getCallingActivity():

Return the name of the activity that invoked this activity. This is who the data in setResult() will be sent to. You can use this information to validate that the recipient is allowed to receive the data.

Note: if the calling activity is not expecting a result (that is it did not use the startActivityForResult(Intent, int) form that includes a request code), then the calling package will be null.

Returns

The ComponentName of the activity that will receive your reply, or null if none.

Hospice answered 25/5, 2013 at 20:46 Comment(4)
If you start the activity with: FLAG_ACTIVITY_NEW_TASK, it doesn't work :( (I had to start the login activity out of context in an error handler). Any other ideas? Thanks!Shep
this doesn't work if the activity is started with a fragment: fragment.getActivity().startActivityForResult(intent, requestCode);Iover
@MarioLenci It works correctly for me. No matter whether I start it from activity or fragment.Sadiras
@MarioLenci because when you are in a fragment, you don’t have to call getActivity().startActivityFor… from a fragment you have to do startActivityForResult directly.Chiffon
P
0

You can parse a boolean with put extra inside an intent.

//First Activity
Intent i = new Intent(FirstActivity.this, SecondActiviy.class);   
boolean isForResult = true;
i.putExtra("for-result", isForResult);

Then on Second Activity get the value:

//Second Activity
boolean isForResult = getIntent().getBooleanExtra("for-result" , false);

This way you know with a global boolean if you start an activity for get a result. If you don't put a boolean extra the default value will be false. Wich means.

//Not necesary at all.
boolean isForResult = false;

You don't need to parse a false boolean.

Paulin answered 5/4, 2021 at 23:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.