I have two android apps, lets call them app A and app B.
Inside app A I create a share intent as follows:
shareIntent=Intent.createChooser(sendIntent, null); // sendIntent contains data to share.
this will be used to pass data to app B.
App B's MainActivity (its only Activity) is configured to have launchMode="singleTask".
Behavior 1:
If from app A I use startActivity(shareIntent) and app B was in background, it comes to foreground and handles the intent with onNewIntent method. If app B wasn't in background it starts a new task for app B with its initial intent set to sendIntent that was passed from app A.
Behavior 2:
If from app A I use startActivityForResult(shareIntent, SUCCESS_CODE) it doesn't matter if app B was in background or not, It is started afresh, moreover the MainActivity of app B is started and pushed to the backStack of app A, it doesn't start in a separate task, after this I have 2 MainActivities of app B, one which I kept in background, and one launched inside app A.
Why does startActivityForResult causes Behavior 2?
What can be done as a developer of app B who has no control over how app A starts it to always show Behavior 1?
You cannot start an
ActivityusingstartActivityForResult()if thatActivityhas launch mode ofsingleTaskorsingleInstance. The reason is thatstartActivityForResult()requires the targetActivity(i: the one being launched) to run in the same task as theActivitythat expects the result.Normally, if you try to launch an
Activityand thatActivityis declared with launch mode ofsingleTaskorsingleInstance, Android automatically addsIntent.FLAG_ACTIVITY_NEW_TASKto theIntentand ensures that the targetActivityis launched in a separate task.If a developer expects that his
Activitywill be launched usingstartActivityForResult()and he codes theActivityto actually return a result, it makes absolutely no sense to declare thisActivitywith launch mode ofsingleTaskorsingleInstance.This behaviour is not what you say you are seeing, but it is clear that there is a conflict between the contract for
startActivityForResult()and launch mode ofsingleTask.