Files
notes/docs/lectures/mdp/04_threads.md
T

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()
  • 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 HandlerThread can 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 Runnable object

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

img

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
    1. Do not block the UI thread
    2. 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

  1. Long(ish)-running code that does not involve the UI
  2. 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;