Why is getCallingActivity always returning null?

后端 未结 6 1264
被撕碎了的回忆
被撕碎了的回忆 2021-01-20 19:06

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

相关标签:
6条回答
  • 2021-01-20 19:13

    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.

    0 讨论(0)
  • 2021-01-20 19:17

    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

    0 讨论(0)
  • 2021-01-20 19:26

    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.

    0 讨论(0)
  • 2021-01-20 19:28

    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").

    0 讨论(0)
  • 2021-01-20 19:33

    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.

    0 讨论(0)
  • 2021-01-20 19:35

    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.

    0 讨论(0)
提交回复
热议问题