Pro Android with Kotlin


CHAPTER 9: User Interface


Download 5.42 Mb.
Pdf ko'rish
bet162/223
Sana04.11.2023
Hajmi5.42 Mb.
#1746807
1   ...   158   159   160   161   162   163   164   165   ...   223
Bog'liq
@de android telegram Pro Android with Kotlin Developing Modern Mobile

192
CHAPTER 9: User Interface
Java Concurrency
At a low level, you can use Java threads and classes from the java.util.concurrent 
package to handle background jobs. Beginning with Java 7, those classes have become 
quite powerful, but you need to fully understand all options and implications.
You will quite often read that directly handling threads from inside the Android OS is not a 
good idea because threads are expensive when speaking of system resources. While this 
was certainly true for older devices and old Android versions, nowadays this is just no longer 
the case. For me, a simple test on a Motorola Moto G4 starting 1,000 threads and waiting 
until all are running took approximately 0.0006 seconds per thread. So, if you are used to 
Java threads and less than a millisecond for the thread to start is good for you, there is no 
performance reason for not using Java threads. However, you must take into account that 
threads run outside any Android component lifecycle, so you have to handle lifecycle issues 
manually if you use threads.
In Kotlin, threads are defined and started easily.
val t = Thread{ ->
// do background work...
}.also { it.start() }
Note that accessing the UI from inside a thread is not allowed in Android. You must do that 
as follows:
val t = Thread{ ->
// do background work...
runOnUiThread {
// use the UI...
}
}.also { it.start() }
The AsyncTask Class
An AsyncTask object is a medium-level helper class to run some code in the background. 
You override its doInBackground() method to do some background work, and if you need to 
communicate with the UI, you also implement onProgressUpdate() to do the communication 
and fire publishProgress() from inside the background work to trigger it.
Caution A number of N AsyncTask jobs will not lead to a parallel execution of all N of them. 
Instead, they all run sequentially in 
one background thread.
Note Android Studio will as a warning complain about a possible memory leak if you create 
AsyncTask objects like val at = object : AsyncTask< Int, Int, Int >() { ... }. 
This is because internally a static reference to the background code will be held. The warning can 
be suppressed by annotating the method with @SuppressLint("StaticFieldLeak").



Download 5.42 Mb.

Do'stlaringiz bilan baham:
1   ...   158   159   160   161   162   163   164   165   ...   223




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling