Decide which activity to start from a subclass of Application

I have a simple application in which before I do anything, I must check whether the user is logged in or not. To do this, I inherited the Application class like this:

public class GBApplication extends Application {
    public void onCreate() {
        if (userIsLoggedIn()) {
            Intent overviewActivity = new Intent(this, Overview.class);

userIsLoggedIn() returns a boolean stored in the SharedPreferences file.

Everything works, but when I press back from the Overview activity, it redirects me to the default activity (MainActivity), and removing it from the AndroidManifest.xml files gives error. Also, I can’t call finish() since this is a non activity class.

How can I terminate my program after I return from the Overview class? I found solutions where they pass a value to the MainActivity, call finish() from there. But this seems to complicated. What else I can do?

This is my application tag in AndroidManifest.xml


Your plan is going to cause problems. Every time your process is created, you are starting an activity, even if an activity is not needed for this particular process.

Displaying a launcher activity — such as in response to the user tapping on a home screen launcher icon — is one way that a process might be created for your app. But there are many others:

  • AlarmManager
  • JobScheduler
  • a Notification
  • a push message (e.g., from Firebase Cloud Messaging)
  • a request sent to a ContentProvider that you export from your app
  • a request sent to a Service that you export from your app
  • a manifest-registered BroadcastReceiver
  • the user returning to your task in the overview screen
  • and so on

In none of those scenarios is displaying this activity necessarily appropriate. Yet, your code will display the activity in all of them, because any time Android forks a process for your app, you display this activity.

Have all of your activities (other than the login one) see if the user is logged in, and route the user to the login activity if that is needed. When the user completes the login, and the login activity finishes, the user is returned to where they were trying to go, whether that is your launcher activity or some other activity (e.g., they returned to your task after your app had been in the background for a while, so your process was terminated, but Android tries to send them back to whatever activity of yours they had been in last).

Leave a Reply

Your email address will not be published. Required fields are marked *