2.2 KiB
2.2 KiB
Threads (and Services)
Activities are regularly transitioned to the background
- i.e. when they are stopped or destroyed
- As the user continues with the task
Thread of Execution
Android applications use a single thread model
- A single thread of execution called main
- Started when a process is created
- Handles and dispatches user interface events
- Drawing the interface, responding to
onClick()
- Drawing the interface, responding to
- Handles activity life cycle events
onCreate(),onDestroy()- For all components in an application
Looper and Handler
HandlerThread - extension of thread with support for looper
Looper
- Each
HandlerThreadcan have one looper - A Java thread dies when the run method returns
- Maintains a message queue
looper.loop()- loops through the message queue and processes waiting messages
Message
- A task to be completed
- Might contain data or a reference to a
Runnableobject
- Might contain data or a reference to a
Handler
- Attached to a looper
- Enqueues messages in the looper message queue
- Handles messages from the message queue
- Thread-safe
- One looper can have many handlers associated with it
If we run code that takes >5 s, the application will appear to hang.
- Put longer-running / non-instantaneous code in a separate thread of execution
- Network access, file access
- 2 rules
- Do not block the UI thread
- Do not access the UI thread from outside the UI thread
- Android view objects are not thread-safe
- Post messages via the Handler to the UI thread's looper
We can programmatically interact with UI components
- e.g.
textField.setText(string) - But cannot call this method from outside the UI thread (rule 2)
Instead, split code into two parts
- Long(ish)-running code that does not involve the UI
- Instantaneous code that does involve the UI
- Which needs to be posted to the UI thread responsible for the view
We need to remember the activity life-cycle; otherwise, we risk having orphaned threads.
AsyncTask and others
Accessing the UI thread from another thread
Activity.runOnUiThread(Runnable);
View.post(Runnable);
View.postDelayed(Runnable, long);
MutableLiveData.postValue;
