
Deep Dive into Android Services
Android O, N and below component lifecycles and background tasks
Introduction
Most sophisticated Android apps have to do something that requires background execution. This means in a Background Thread, and not the main thread (which is used for all UI updates).
If you create a Thread or an Executor in an Activity of your app, this leads to unpredictable results, since a simple screen orientation change will disrupt things, since the Activity will no longer be around when the Thread completes its task.
You could use AsyncTask to handle this, but what if your app needs this Background Thread to be started from not just an Activity, but a notification or another component?
In these cases, Android Services are the right Android component to use to match up the Thread’s lifecycle with that of the Service’s lifecycle.
A Service is an Android application component without a UI that runs on the main thread (of the hosting process). It also has to be declared in the AndroidManifest.xml. If you want the service code to run in a Background Thread, then you must manage that yourself. The terms background
and foreground
are overloaded, and can apply to:
- Lifecycle of Android components.
- Threads.
Please read the full article here: https://developerlife.com/2017/07/10/android-o-n-and-below-component-lifecycles-and-background-tasks/