I have a welcome screen that can be started as the first activity in my app, or it can be started by the main activity that the user spends their time in. I want it to act s
I was experiencing this problem when the activity was declared with singleInstance
as launch mode in the manifest. In my case, I found a solution without this declaration which fixed the problem.
it's possible your calling activity is finishing sooner than you're expecting it to. this happened to me and resulted in a null return from getCallingActivity, even though the calling activity was using startActivityForResult
getCallingActivity
can return null
depending on the activity launch mode as others have pointed out. I was launching the activity by calling startActivityForResult
passing in the intent returned by getLaunchIntentForPackage()
. By default, it has the FLAG_ACTIVITY_NEW_TASK
flag set and this caused the getCallingActivity
to return null
. Calling intent.setFlags(0)
solved the problem for me.
It's a known issue: getCallingActivity() returns actual data only if the activity has been started in the same task (see the "Tasks and Back Stack" tutorial). Same goes for starting activities for result properly (they can't be single-instanced and you can't use "FLAG_ACTIVITY_NEW_TASK").
Everyone seems to be pointing to the same solution but nobody is putting it in clear words. Let me do that.
It seems like getCallingActivity() returns results inconsistently across different android platforms.
The issue is caused probably because you are setting the launchMode of your activity as singleInstance or singleTask. Setting it to singleTop or leaving it as the standard one should solve your issue. Of course, changing the mode should not affect your use case so this is at your discretion.
In case it does affect your use case, you can pass the package name in the extras of the intent to simplify things.
Note that setting singleInstance or singleTask returns non null results on Lollipop release.
Pass an extra in the Intent
used with startActivityForResult()
, indicating which mode you want. Read that extra via getIntent().getXXXExtra()
(XXX
depends on what data type you choose) in onCreate()
of the newly-started activity.