One of the most common patterns in app development is to have a LoginActivity which transitions to the MainActivity. Once the user has entered the correct credentials, the app starts the MainActivity and finishes the LoginActivity. The problem is, next time when the user launches your app, you don’t want them to have to login again.

There’s a few different approaches you can take, the easiest one being just force them to login every time they use your app. But, that’s a pretty horrible user experience. Typically you should be saving some kind of token that was returned when the user logs in, and storing it somewhere outside the lifecycle of the app.

Once you have the token, you can keep them logged in until the token expires. In the past what I’ve done is either set the LoginActivity or MainActivity as main in the manifest. If the LoginActivity is set as main, I check if there is a token stored and if so, start MainActivity and call finish. If instead MainActivity is set as main, I do a check if there is no token stored, and if so start the LoginActivity and call finish.

This approach works, but it’s a bit clunky and slow. I discovered another approach, using the NoDisplay theme. With it, I create another activity called MainEmptyActivity. It determines which activity should be started. It looks like this:

Then I add it to the manifest as follows:

As part of this flow, it’s important to consider the token may expire. If it does, you should send them back to the login activity and delete the token from your storage. Usually you would check for a 401 from any request and consider that as a token expired, but responses may vary.

You can also apply this approach to any number of states, the 2 states of login and main are simply the most common. You can do do whatever checks you want in your empty activity and transition from there.

Alternatively, you can use a splash screen instead of the NoDisplay theme.

Whether you keep the display UI free or add in a splash screen is up to you though. The flow remains the same either way.

If You Enjoyed Reading, Please Click That Little Heart. If You Want To Read More Like This, Follow Me On Medium. Thanks!