Launch Second Screen

Learn and practice how to simulate a long-running operation and open a new screen in this lesson.

Flow overview

When a user clicks the login button we will perform a data validation flow, and if the data is valid, proceed to:

  1. Simulate long-running operation for 2 seconds
  2. Open MainActivity
  3. Finish LoginActivity

Simulate a long-running operation

In this lesson, we are not going to do a real login HTTP call, so let’s just simulate it via delay of 2 seconds before opening MainActivity. In a real application, we would need to create an HTTP client to send login data and retrieve a response from the backend REST service.

To perform a delay we can use the Handler object.

In Android, the Handler is an object which is tied to the looper of the thread in which it’s been created. It typically has two use-cases:

  1. If we want to execute code on the main thread
  2. If we want to execute code with a delay or at the specific time

Let’s modify our performLogin method and create a Handler object at the very end. Now we can use this object’s postDelayed method to execute code with a delay. This method has two parameters:

  • The Runnable that will be executed (presented as lambda in the code below)
  • The delay (in milliseconds) until the Runnable will be executed

Get hands-on with 1200+ tech skills courses.