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:
- remove the LAUNCHER category as defined in my AndroidManifest.xml
- create a custom Application class that the app uses
- 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));
}
Why not have an initial
Activity
with no UI that checks the condition in itsonCreate
, then launches the nextActivity
, then callsfinish()
on itself? I've never calledfinish()
from withinonCreate()
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
:Other
Activity
:Here's what I personally did for one of my small mobile projects. Instead of creating a separate, screen-less
Activity
where the condition is and which launches the corresponding screen, I put the condition in oneActivity
and did a dynamicsetContentView()
, as in:Two important notes to this approach:
1: Instead of writing that in
onCreate()
, you want to put the decision-making insideonResume()
precisely because the latter is always called whenever the screen needs to be displayed in front. You can see that from the Android activity life cycle. So if, for example, the user just downloaded my app and launched it for the first time, because no user is logged in, she will be led to the signup page. When she's done signing up and for some reason presses theHOME
button (notBACK
, which exits the app altogether!) and then resumes the app, the layout that she will see is already the home screen's. If I put the conditional insideonCreate()
, what would have been displayed is the sign up screen because according to the life cycle, it doesn't go back toonCreate()
when bringing back an app to the front.2: This solution is ideal only if merging the functionalities of those two Activities would not produce a long diabolical block of code. Like I said, my project was a small one (its primary feature occurs in the background), so that single dynamic
Activity
didn't have too much in it. The screen-lessActivity
is definitely the way to go if you need your code to be more human-readable.