Android: creating a “first time user” activity

2020-03-26 12:10发布

问题:

I want to have an activity with registration for the users who run my app for the very first time. I don't want the user to be able to go past this registration activity, if he doesn't want to register, he has to close the app.

I can check whether the user is registered by storing the in SharedPreferences, that seems to work without any problems. So what I have so far in my MainActivity:

public void onCreate(Bundle savedInstanceState) {
    if (needsRegistration()) {
        Intent intent = new Intent(this, RegistrationActivity.class);
        startActivity(intent);
    }

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ...
}

I am having the following problems with this:

  • I am not sure where I should start the registration activity (before or after super.onCreate(savedInstanceState) ?)
  • The MainActivity seems to keep working in the background and creates errors (because the user is not registered)
  • The user can go to the MainActivity by pressing the back button

What is the proper way to do this?

回答1:

I am not sure where I should start the registration activity (before or after super.onCreate(savedInstanceState) ?)

You should have your super() call as the first call when doing opening functions like onCreate(), onResume(), etc.... This way the function can do everything that the super() call needs to in order for the function to be ready. This isn't always a problem but safer to make the call first. Finishing functions such as onBackPressed(), finish(), etc... should have the super() call after you do your cleanup such as saving data.

The MainActivity seems to keep working in the background and creates errors (because the user is not registered)

Make the RegistrationActivity the launcher Activity and check if the user is registered and if so start the MainActivity else display your registration code or whatever you do in this case.

The user can go to the MainActivity by pressing the back button

See the previous solution. If the MainActivity is only started from the RegistrationActivity then this won't be an issue.

Checking the SharedPreferences to see if the user is registered shouldn't cause much of a delay so you can do this before creating the layout for that Activity and go to the MainActivity if they are registered. If for some reason you are noticing much of a delay then you can make a splash screen to show your logo or whatever while you check for registered or not then take appropriate actions by going to either the registration or main Activity.