Android – How To Run Android Tasks In Background Threads ?

Hello Readers, CoolMonkTechie heartily welcomes you in this article (How To Run Android Tasks In Background Threads ?).

In this article, we will learn about how to run android tasks in background threads. All Android apps use a main thread to handle UI operations. Calling long-running operations from this main thread can lead to freezes and unresponsiveness. For example, if our app makes a network request from the main thread, our app’s UI is frozen until it receives the network response. We can create additional background threads to handle long-running operations while the main thread continues to handle UI updates.

This article shows both Kotlin and Java Programming Language developers to use of a thread pool to set up and use multiple threads in an Android app. It also explains code definitions to run on a thread and communications between one of these threads and the main thread.

A famous quote about learning is :

That is what learning is. You suddenly understand something you’ve understood all your life, but in a new way.

So Let’s begin.

Overview

In this example section, we will make a network request and return the result to the main thread, where the app then might display that result on the screen. Specifically, the ViewModel calls the repository layer on the main thread to trigger the network request. The repository layer is in charge of moving the execution of the network request off the main thread and posting the result back to the main thread using a callback.

To move the execution of the network request off the main thread, we need to create other threads in our app.

Creating Multiple Threads

thread pool is a managed collection of threads that runs tasks in parallel from a queue. New tasks are executed on existing threads as those threads become idle. To send a task to a thread pool, use the ExecutorService interface. Note that ExecutorService has nothing to do with Services, the Android application component.

Creating threads is expensive, so we should create a thread pool only once as our app initializes. Be sure to save the instance of the ExecutorService either in our Application class or in a dependency injection container. The following example creates a thread pool of four threads that we can use to run background tasks.

class MyApplication : Application() {
    val executorService: ExecutorService = Executors.newFixedThreadPool(4)
}

Executing In A Background Thread

Making a network request on the main thread causes the thread to wait, or block, until it receives a response. Since the thread is blocked, the OS can’t call onDraw(), and our app freezes, potentially leading to an Application Not Responding (ANR) dialog. Instead, let’s run this operation on a background thread.

First, let’s take a look at our Repository class and see how it’s making the network request:

sealed class Result<out R> {
    data class Success<out T>(val data: T) : Result<T>()
    data class Error(val exception: Exception) : Result<Nothing>()
}

class LoginRepository(private val responseParser: LoginResponseParser) {
    private const val loginUrl = "https://example.com/login"

    // Function that makes the network request, blocking the current thread
    fun makeLoginRequest(
        jsonBody: String
    ): Result<LoginResponse> {
        val url = URL(loginUrl)
        (url.openConnection() as? HttpURLConnection)?.run {
            requestMethod = "POST"
            setRequestProperty("Content-Type", "application/json; charset=utf-8")
            setRequestProperty("Accept", "application/json")
            doOutput = true
            outputStream.write(jsonBody.toByteArray())

            return Result.Success(responseParser.parse(inputStream))
        }
        return Result.Error(Exception("Cannot open HttpURLConnection"))
    }
}

makeLoginRequest() is synchronous and blocks the calling thread. To model the response of the network request, we have our own Result class.

The ViewModel triggers the network request when the user taps, for example, on a button:

class LoginViewModel(
    private val loginRepository: LoginRepository
) {
    fun makeLoginRequest(username: String, token: String) {
        val jsonBody = "{ username: \"$username\", token: \"$token\"}"
        loginRepository.makeLoginRequest(jsonBody)
    }
}

With the previous code, LoginViewModel is blocking the main thread when making the network request. We can use the thread pool that we’ve instantiated to move the execution to a background thread. First, following the principles of dependency injectionLoginRepository takes an instance of Executor as opposed to ExecutorService because it’s executing code and not managing threads:

class LoginRepository(
    private val responseParser: LoginResponseParser
    private val executor: Executor
) { ... }

The Executor’s execute() method takes a Runnable. A Runnable is a Single Abstract Method (SAM) interface with a run() method that is executed in a thread when invoked.

Let’s create another function called makeLoginRequest() that moves the execution to the background thread and ignores the response for now:

class LoginRepository(
    private val responseParser: LoginResponseParser
    private val executor: Executor
) {

    fun makeLoginRequest(jsonBody: String) {
        executor.execute {
            val ignoredResponse = makeSynchronousLoginRequest(url, jsonBody)
        }
    }

    private fun makeSynchronousLoginRequest(
        jsonBody: String
    ): Result<LoginResponse> {
        ... // HttpURLConnection logic
    }
}

Inside the execute() method, we create a new Runnable with the block of code, we want to execute in the background thread—in our case, the synchronous network request method. Internally, the ExecutorService manages the Runnable and executes it in an available thread.

In Kotlin, we can use a lambda expression to create an anonymous class that implements the SAM interface.

Considerations

Any thread in our app can run in parallel to other threads, including the main thread, so we should ensure that our code is thread-safe. Notice that in our example that we avoid writing to variables shared between threads, passing immutable data instead. This is a good practice, because each thread works with its own instance of data, and we avoid the complexity of synchronization.

If we need to share state between threads, we must be careful to manage access from threads using synchronization mechanisms such as locks. In general we should avoid sharing mutable state between threads whenever possible.

Communicating With The Main Thread

In the previous step, we ignored the network request response. To display the result on the screen, LoginViewModel needs to know about it. We can do that by using callbacks.

The function makeLoginRequest() should take a callback as a parameter so that it can return a value asynchronously. The callback with the result is called whenever the network request completes or a failure occurs. In Kotlin, we can use a higher-order function.

class LoginRepository(
    private val responseParser: LoginResponseParser
    private val executor: Executor
) {

    fun makeLoginRequest(
        jsonBody: String,
        callback: (Result<LoginResponse>) -> Unit
    ) {
        executor.execute {
            try {
                val response = makeSynchronousLoginRequest(jsonBody)
                callback(response)
            } catch (e: Exception) {
                val errorResult = Result.Error(e)
                callback(errorResult)
            }
        }
    }
    ...
}

The ViewModel needs to implement the callback now. It can perform different logic depending on the result:

class LoginViewModel(
    private val loginRepository: LoginRepository
) {
    fun makeLoginRequest(username: String, token: String) {
        val jsonBody = "{ username: \"$username\", token: \"$token\"}"
        loginRepository.makeLoginRequest(jsonBody) { result ->
            when(result) {
                is Result.Success<LoginResponse> -> // Happy path
                else -> // Show error in UI
            }
        }
    }
}

In this example, the callback is executed in the calling thread, which is a background thread. This means that we cannot modify or communicate directly with the UI layer until we switch back to the main thread.

To communicate with the View from the ViewModel layer, use LiveData as recommended in the updated app architecture. If the code is being executed on a background thread, we can call MutableLiveData.postValue() to communicate with the UI layer.

Using Handlers

We can use a Handler to enqueue an action to be performed on a different thread. To specify the thread on which to run the action, construct the Handler using a Looper for the thread. A Looper is an object that runs the message loop for an associated thread. Once we’ve created a Handler, we can then use the post(Runnable) method to run a block of code in the corresponding thread.

Looper includes a helper function, getMainLooper(), which retrieves the Looper of the main thread. We can run code in the main thread by using this Looper to create a Handler. As this is something we might do quite often, we can also save an instance of the Handler in the same place we saved the ExecutorService:

class MyApplication : Application() {
    val executorService: ExecutorService = Executors.newFixedThreadPool(4)
    val mainThreadHandler: Handler = HandlerCompat.createAsync(Looper.getMainLooper())
}

It’s a good practice to inject the handler to the Repository, as it gives us more flexibility. For example, in the future we might want to pass in a different Handler to schedule tasks on a separate thread. If we’re always communicating back to the same thread, we can pass the Handler into the Repository constructor, as shown in the following example.

class LoginRepository(
    ...
    private val resultHandler: Handler
) {

    fun makeLoginRequest(
        jsonBody: String,
        callback: (Result<LoginResponse>) -> Unit
    ) {
          executor.execute {
              try {
                  val response = makeSynchronousLoginRequest(jsonBody)
                  resultHandler.post { callback(response) }
              } catch (e: Exception) {
                  val errorResult = Result.Error(e)
                  resultHandler.post { callback(errorResult) }
              }
          }
    }
    ...
}

Alternatively, if we want more flexibility, we can pass in a Handler to each function:

class LoginRepository(...) {
    ...
    fun makeLoginRequest(
        jsonBody: String,
        resultHandler: Handler,
        callback: (Result<LoginResponse>) -> Unit
    ) {
        executor.execute {
            try {
                val response = makeSynchronousLoginRequest(jsonBody)
                resultHandler.post { callback(response) }
            } catch (e: Exception) {
                val errorResult = Result.Error(e)
                resultHandler.post { callback(errorResult) }
            }
        }
    }
}

In this example, the callback passed into the Repository’s makeLoginRequest call is executed on the main thread. That means we can directly modify the UI from the callback or use LiveData.setValue() to communicate with the UI.

Configuring A Thread Pool

We can create a thread pool using one of the Executor helper functions with predefined settings, as shown in the previous example code. Alternatively, if we want to customize the details of the thread pool, we can create an instance using ThreadPoolExecutor directly. We can configure the following details:

  • Initial and maximum pool size
  • Keep alive time and time unit. Keep alive time is the maximum duration that a thread can remain idle before it shuts down.
  • An input queue that holds Runnable tasks. This queue must implement the BlockingQueue interface. To match the requirements of our app, we can choose from the available queue implementations.

Here’s an example that specifies thread pool size based on the total number of processor cores, a keep alive time of one second, and an input queue.

class MyApplication : Application() {
    /*
     * Gets the number of available cores
     * (not always the same as the maximum number of cores)
     */
    private val NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors()

    // Instantiates the queue of Runnables as a LinkedBlockingQueue
    private val workQueue: BlockingQueue<Runnable> =
            LinkedBlockingQueue<Runnable>()

    // Sets the amount of time an idle thread waits before terminating
    private const val KEEP_ALIVE_TIME = 1L
    // Sets the Time Unit to seconds
    private val KEEP_ALIVE_TIME_UNIT = TimeUnit.SECONDS
    // Creates a thread pool manager
    private val threadPoolExecutor: ThreadPoolExecutor = ThreadPoolExecutor(
            NUMBER_OF_CORES,       // Initial pool size
            NUMBER_OF_CORES,       // Max pool size
            KEEP_ALIVE_TIME,
            KEEP_ALIVE_TIME_UNIT,
            workQueue
    )
}

Concurrency Libraries

It’s important to understand the basics of threading and its underlying mechanisms. There are, however, many popular libraries that offer higher-level abstractions over these concepts and ready-to-use utilities for passing data between threads. These libraries include Guava and RxJava for the Java Programming Language users and coroutines, which we recommend for Kotlin users.

In practice, we should pick the one that works best for our app and our development team, though the rules of threading remain the same.

That’s all about in this article.

Related Other Articles / Posts

Conclusion

In this article, we understood about how to run android tasks in background threads. This article showed both Kotlin and Java Programming Language developers to use of a thread pool to set up and use multiple threads in an Android app. It also explained code definitions to run on a thread and communications between one of these threads and the main thread.

Thanks for reading! I hope you enjoyed and learned about Running Android Tasks In Background Threads concepts. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe to the blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

You can find other articles of CoolMonkTechie as below link :

You can also follow official website and tutorials of Android as below links :

If you have any comments, questions, or think I missed something, leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

Exit mobile version