When is it necessary to use singleTop launchMode in an android widget or application?

mobibob picture mobibob · Jul 16, 2010 · Viewed 39.2k times · Source

I just got burned by a widget. I could see the cause of the problem, but I could not determine why or its solution. My widget was issuing a search (SearchManager) and the activity launched a search dialog, but when it called-back to my widget, it created another reference to the widget (i.e., the thread-id was the same, but the widget-id changed from 65 to 0).

This led me to believe that a new instance was getting created and I searched the documentation for settings that would apply to the problem. Eventually, I stumbled upon the android:launchMode="singleTop" and as soon as I set it in the AndroidManifest, viola! My widget worked.

This took me the better part of two days to debug.

Are there any other situations or is there a more technically-correct answer to my problem?

Answer

mobibob picture mobibob · Jul 19, 2010

I did more reading in Android Docs -- I could spend a lifetime reading their docs and find a new subtle detail that breaks my brain :) This explains my multiple-instances that I did not expect, however, I configured to occur.

Android Doc on Activity definition for AndroidManifest.xml

The "standard" and "singleTop" modes differ from each other in just one respect: Every time there's new intent for a "standard" activity, a new instance of the class is created to respond to that intent. Each instance handles a single intent. Similarly, a new instance of a "singleTop" activity may also be created to handle a new intent. However, if the target task already has an existing instance of the activity at the top of its stack, that instance will receive the new intent (in an onNewIntent() call); a new instance is not created. In other circumstances — for example, if an existing instance of the "singleTop" activity is in the target task, but not at the top of the stack, or if it's at the top of a stack, but not in the target task — a new instance would be created and pushed on the stack.