129
CHAPTER 8: APIs
Java threads
Java and Kotlin threads (remember, both are targeting the same Java virtual
machine) are a low-level technique of running things in the background. In
Kotlin you can use a construct as easy as this to process program parts in
a background thread:
Thread{-> do s.th.}.start()
This is a basic approach, and you can expect high performance from your
background execution tasks. However, you are completely running out
of any Android OS component lifecycle, so you do not really have good
control of what happens to long-running background threads while the
lifecycle status of Android processes changes.
Java concurrency classes
Java and Kotlin allow the use of concurrency-related classes from the
java.util.concurrency package. This is a higher-level approach of running
things in the background with improved background tasks management
capabilities, but it still has the downside of running beyond the control of
the Android component lifecycle.
AlarmManager
This was originally designed for running tasks at specific times, and you can
use it if you need to send notifications to the user at specific instances in time.
It has been there since API level 1. Starting at API level 19 (Android 4.4),
the system allows for postponing alarms under certain conditions. The
downside is you don’t have control over more general device conditions;
when the device is up, it will fire alarm events at its own discretion, no
matter what else happens on your device.
SyncAdapter
This methodology was added in Android API level 5. It is particularly useful
for synchronization tasks. For more general background execution tasks,
you should instead use one of the following two, Firebase JobDispatcher
or JobScheduler. Use one of these only if you need one of the additional
functionalities it provides.
Do'stlaringiz bilan baham: |