Dynamic start activity in Android?

Matt Huggins picture Matt Huggins · Jan 31, 2011 · Viewed 14.1k times · Source

Is there a way to dynamically change the starting activity in Android based upon a conditionally? What I attempted to do (that didn't work) was the following:

  1. remove the LAUNCHER category as defined in my AndroidManifest.xml
  2. create a custom Application class that the app uses
  3. override the onCreate method of my Application class to define some code like the following:

.

if (condition) {
    startActivity(new Intent(this, MenuActivity.class));
} else {
    startActivity(new Intent(this, LoginActivity.class));
}

Answer

dave.c picture dave.c · Jan 31, 2011

Why not have an initial Activity with no UI that checks the condition in its onCreate, then launches the next Activity, then calls finish() on itself? I've never called finish() from within onCreate() though, so I'm not sure if this will work.

EDIT
Seems to work fine. Here's some code to make it clearer.
Initial Activity:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Intent intent;
    if (condition) {
       intent = new Intent(this, ClassA.class);
    } else {
       intent = new Intent(this, ClassB.class);
    }
    startActivity(intent);
    finish();
    // note we never called setContentView()
}

Other Activity:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}