Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - startActivityForResult immediately triggering onActivityResult

People also ask

Is startActivityForResult deprecated?

onActivityResult , startActivityForResult , requestPermissions , and onRequestPermissionsResult are deprecated on androidx.

What is the replacement for startActivityForResult?

Among the contracts available, the StartActivityForResult contract is the replacement to the startActivityForResult . The callback is to be called once the activity result is available.

How does onActivityResult work on Android?

The android startActivityForResult method, requires a result from the second activity (activity to be invoked). In such case, we need to override the onActivityResult method that is invoked automatically when second activity returns result.


You can't use startActivityForResult() if your activity is being launched as a singleInstance or singleTask. standard or singleTop launch mode will fix the problem.


Additionally make sure the intent does not have the Intent.FLAG_ACTIVITY_NEW_TASK set.

From the docs:

This flag can not be used when the caller is requesting a result from the activity being launched.


I have seen this behavior before, please make sure your destnation activity (that special activity) is not singleInstance in AndroidManifest file. If the Activity is singleInstance, then it will return RESULT_CANCELED before launched!


I'd also like to add that you could call an external app with:
Intent in = caller.getPackageManager().getLaunchIntentForPackage("com.your.package.here");
Which would create an intent with Intent.FLAG_ACTIVITY_NEW_TASK added by default, so call:
in.setFlags(0);
Which will clear that flag, and then you can proceed to: startActivityForResult(in, action);

Reason I'm doing this is that I have a utility app that has common functionality between a few other apps and I can keep the code changes to one location instead of worrying about multiple updates.


startActivityForResult() doesn't work with a singleInstance or singleTask activity in pre-lollipop version of Android. Since Android 5 it works (see this answer for more details).


It also triggers if you have FLAG_ACTIVITY_NEW_TASK in your intent.

Intent intent = new Intent(this, MyActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivityForResult(intent, REQUEST_CODE);

My problem was with the calling activity. Its declaration in the AndroidManifest had the following property:

android:noHistory="true"

Changed it to "false" and now works fine.