I’m trying to write an android application that has two main activities: login screen and display screen. Currently I’m setting it up so that if the user is already logged in, the login screen will be skipped.
In order to work out the best way to do this, I created a generic “Main” activity that looks something like this:
public class Main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
// Get preferences
SharedPreferences settings = getSharedPreferences("PREFERENCES", MODE_PRIVATE);
super.onCreate(savedInstanceState);
//setContentView(R.layout.viewusage);
//System.out.println(settings.getBoolean("LOGGEDIN", false));
if (settings.getBoolean("LOGGEDIN", false) == false)
{
Intent intent = new Intent(Main.this, Login.class);
startActivity(intent);
}
else
{
Intent intent = new Intent(Main.this, Display.class);
startActivity(intent);
}
}
}
The idea is when someone logs in successfully, the login activity will save all the details needed to the user preferences, and then finish() the activity. This will return to the Main activity. What I’m trying to do is have the main activity keep looping through the if … else statement when there aren’t any activities running: so when the login page closes, it will re-run the if … else statement, and should launch the Display activity rather than the Login activity. The reverse will be true if the user logs out from the Display class.
I’ve thought of using a while (true) loop, but that just hangs the program. I’ve thought of putting it in a separate thread, but I don’t know how to detect if there is already another activity running, so a separate thread will just keep looping and opening new activities (I presume, I haven’t tried it)
Any suggestion on how I could work this out?
Thanks.
You can’t do it by looping in
onCreate, because the activity doesn’t actually get off the ground untilonCreatereturns.One possibility is to use
startActivityForResultand arrange for the Login and Display activities to return a code indicating whether to quit or proceed to the other activity. Then you would place your logic inonActivityResultinstead of looping inonCreate.Another, perhaps cleaner approach is to design the Display activity to directly start the Login activity when the user logs out, and vice versa. That way, the Main activity can just call
finish()after it determines which activity to display initially.