Can my app's main Activity be bypassed on launch?

by eehouse » Mon, 10 May 2010 04:29:19 GMT

Sponsored Links
 Are there any scenarios on Android where a process can be instantiated
(classes loaded, etc.) and a non-main activity launched without going
through the main activity?

Background: my app has a single main activity
(android:name="android.intent.action.MAIN" and
android:name="android.intent.category.LAUNCHER"), some secondary
activities, and a preferences class providing static methods meant to
be called from anywhere.  These static methods' implementations
require a Context, and so the class has a static Context member
s_context; the static methods assert that s_context is non-null before
using it.  The very first thing I do in my main activity's onCreate()
method is pass getApplicationContext() into the preferences class so
it can set s_context.

The main activity launches a secondary activity that calls the
preference class's static methods.  Sometimes -- never in an emulator,
and only after my app's been running for a while and moved to the
background several times -- those asserts fail.

This indicates that somehow the secondary activity is running but that
the main activity never ran.  (Or that the preferences class was gc'd
and reloaded, but java doesn't work that way AFAIK.)  Is it possible
that Android is launching my app directly into the secondary activity,
e.g. because that's that activity that was running when it was killed?

Alternatively, is there a way my main activity can be launched and its
onCreate() not called?  I'm just beginning to read about singleTop and
other alternative launch modes.  I'm not setting these at the




Can my app's main Activity be bypassed on launch?

by Mark Murphy » Mon, 10 May 2010 04:35:35 GMT


Sure. The process may have been terminated to reclaim memory, then
reconstituted when the user, say, BACK-buttons to the activity.

Mutable static data members should be avoided where possible, used in a
very transient fashion if needed, or at most used as a non-essential cache.

That is supremely dangerous, as you can introduce a substantial memory
leak. Not to mention it is causing the problem you are experiencing.
Please just pass in a Context to the static helper methods.

See above, plus there is no need to use getApplicationContext() ever,
hardly. An Activity is a Context. A Service is a Context.

This is not surprising. Please just pass in a Context to your static
helper methods.

Mark Murphy (a Commons Guy)  |  | 

Android Online Training: 21-25 June 2010: 


Sponsored Links