• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps launchMode problems

D

Deleted User

Guest
Hi,

I've read the Android documentation, watched a couple videos on YouTube and read through a few relevant forum posts. I feel like I have a good understanding of the Activity lifecycle and how to manipulate the Activity stack. At this point, I'm either wrong or the Android SDK is broken (yes, it's likely the former).

1) The way I understand launchMode="singleTop" is that calling startActivity on a new Activity will pull an existing instance of that Activity from the Activity stack (if one exists) and place it on top as long as you don't add the FLAG_ACTIVITY_NEW_TASK flag to the Intent. I've also read that if you hit the back button while on a singleTop Activity, that Activity will be destroyed. My problem is: I've set singleTop on several Activities and they always have a new instance created when I call startActivity. I am not hitting the back button. I'm using an Options Menu I've created to navigate around. I've even tried adding FLAG_ACTIVITY_SINGLE_TOP in code and it still creates a new instance of the Activity. The old one is still on the stack. Why???

2) I've also tried using launchMode="singleInstance" to force a single instance of an Activity. This works as expected. Only one instance of those Activities is ever created. However, this also causes problems. For one, pressing the home button and re-launching the app takes me to my MAIN Activity instead of the last Activity I was on. I've read in the Android documentation that this is expected behavior. I think it's silly, but I digress. What really breaks is using startActivityForResult. If an Activity is marked singleInstance and it calls startActivityForResult on a new Activity, the onActivityResult handler fires immediately (before the new Activity is even created). The new Activity then gets created and when the user performs whatever action to return the result, the onActivityResult handler does not fire. Why???
 
So it looks like, via the Android documentation, that startActivityForResult automatically returns a cancel message when the launchMode is singleTask or singleInstance. For whatever reason, they don't want you to do this.

It sounds like, if you have a ListActivity and another screen (so that you can create multiple instances of your ListActivity via natural navigation, the common method is to create a singleton that holds your list data and you override the onResume handler and [clear and] populate the ListView with the data from the singleton. Does this sound wrong to anybody?
 
Upvote 0

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones