Background work in Android

Background work in Android

Background work

Each and every Android application deals with data and processing that data is one of the most important part. Generally, we should take any blocking tasks off the UI thread. The long-running tasks like decoding a bitmap, accessing storage, working on a ML (Machine Learning) model or network requests all these tasks should be moved off the UI thread to the Background Thread. An app is running in the background when none of the app's activities are currently visible to the user and the app isn't running any foreground services that started while an activity from the app was visible to the user.

Types of Background work

Background work are categorised primarily into three categories :-

  • Immediate : Tasks that needs to execute right away and complete asap.
  • Long Running : Tasks that may take some time to complete
  • Deferrable : Tasks that does not need to run right away

Likewise, Work is also categories into two categories,

  • Persistent work : Work that remains scheduled even if the app restarts and device reboots.
  • Impersistent work : Work that does not remain scheduled after the process ends.

Types of background work

Immediate work

Immediate work consists of tasks which need to execute right away. These are tasks which are important to the user to remain scheduled for prompt execution even if the app closes or the device restarts.

Solution

  • For Persistent immediate work : we should use WorkManager with a OneTimeWorkRequest. Expedite a WorkRequest with setExpedited()
  • For Impersistent immediate work : we should use Kotlin coroutines. If our app is using Java then we should use RxJava or Guava or Executors.

Long-running work

Long-running work are basically tasks which are likely to take more than ten minutes to complete. As the name suggests, all long running tasks falls into this category.

Solution

WorkManager allows us to handle such tasks using a long-running Worker that we can use to run these time-consuming long-running tasks in the background thread.

Deferrable work

Deferrable work is basically any work that does not need to run right away or has lesser urgency.

Solution

Deferrable work can be scheduled through WorkManager. this is the best way to handle tasks that don't need to run immediately but which ought to remain scheduled when the app closes or the device restarts.

❤️Finally

I hope this article was worth reading and you've learnt about background work and it's types. If you've any questions or suggestions, let me know in the comments and also leave a clap if you think it was helpful. Don't forget to share !!!

Thanks :) Be safe, Keep coding. Cheers!

Did you find this article valuable?

Support Gajendra Singh Rathore by becoming a sponsor. Any amount is appreciated!