Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 14

Software for Mobile Devices

Broadcast Listeners, Processes & Threads


(Part2)
Lecture # 17

Online Group Piazza: https://piazza.com/fast_lahore/fall2018/cs440/home


Access Code: cs440
Processes and Threads!

1. When an application component starts and the application does not have any
other components running, the Android system starts a new Linux process.

2. If an application component starts and there already exists a process for that
application (because another component from the application exists), then
the component is started within that process and uses the same thread of
execution.

3. By default, all components of the same application run in the same process
and thread (called the "main" thread).

4. However, you can arrange for different components in your application to run
in separate processes, and you can create additional threads for any process.

5. You can specify android:process=":anyname" in your manifest to have an


activity/service run in a seperate process.

6. Process lifecycle:
https://developer.android.com/reference/android/app/Activity#ProcessLifecy
cle
Lifecycle
• The Android system attempts to keep an application process around for
as long as possible, but eventually will need to remove old processes
when memory runs low.

• The system will kill less important processes (the last ones) before it resorts
to killing more important processes (the first ones).

Process Lifecycle
• Essential Four States:
1. Foreground Activity: If an activity is in the foreground of the screen
2. Visible Activity: If an activity has lost focus but is still visible
3. Background Activity: If an activity is completely obscured by another activity, it
is stopped.
4. Empty Process: If an activity is paused or stopped, the system can drop the
activity from memory by either asking it to finish, or simply killing its process.

Sometimes an Activity may need to do a long-running operation that exists independently of the activity lifecycle itself. Use
Service (this allows the system to properly prioritize your process )
Processes and Threads!

Communication between process will be done by IPC


(Messenger or AIDL)
Message Queue, Looper, Handler

MessageQueue is a message loop or message queue which basically contains a list of Messages or
Runnables (set of executable code).
Looper loops through message queue and sends messages to corresponding handlers to
process.

https://github.com/AnilDeshpande/UIThreadDemo/t
https://www.youtube.com/watch?v=fZTJflHJoBY ee/handler-code
Message Queue, Looper, Handler

A handler has two purposes:


• Send messages to a looper message queue from any thread.
• Handle messages dequeued by a looper on the thread associated to that looper.

https://www.youtube.com/watch?v=LJ_pUlWzGsc
Main Thread

1. When an application is launched, the system creates a thread of execution for the
application, called "main thread/ UI thread."

2. It is in-charge of dispatching events to the appropriate user interface widgets,


including drawing events.

3. All components that run in the same process are instantiated in the UI thread, and
system calls to each component are dispatched from that thread.

4. When the user touches a button on the screen, your app's UI thread dispatches the
touch event to the widget, which in turn sets its pressed state and posts an invalidate
request to the event queue. The UI thread dequeues the request and notifies the
widget that it should redraw itself.

5. App performing intensive work can yield poor performance. (If everything is
happening in the UI Thread)
Main Thread

1. When the thread is blocked, no events can be dispatched, including drawing events

2. UI thread is blocked for more than a few seconds (about 5 seconds currently) the
user is presented with the infamous "application not responding" (ANR) dialog.

3. Android UI toolkit is not thread-safe. (must not manipulate your UI from a worker
thread)

4. Thus, there are simply two rules to Android's single thread model:
1. Do not block the UI thread
2. Do not access the Android UI toolkit from outside the UI thread
Worker Threads

1. People use the word "worker" when they mean a thread that does not own or
interact with UI.

2. So what we need are background/worker threads to perform background


operations. But you cannot update your UI from these (background/worker) threads.

3. There should be no explicit reference to UI components in these threads.

4. Problem Scenario 1: View objects contain references to the activity that owns them.
If that activity is destroyed, but there remains a threaded block of work that
references it—directly or indirectly—the garbage collector will not collect the activity
until that block of work finishes executing.

5. Problem Scenario 2: Consider an app that holds a direct reference to a UI object on


a worker thread. The object on the worker thread may contain a reference to a
View; but before the work completes, the View is removed from the view hierarchy.
When these two actions happen simultaneously, the reference keeps the View
object in memory and sets properties on it. However, the user never sees this object,
and the app deletes the object once the reference to it is gone.
Worker Threads

Working in
background

Any code here would work This part works on a UI Thread.


in background/worker
thread.
With in a worker thread, we can access UI in thread by
using runOnUiThread method.
Worker Threads - The best way?

In all cases, your app should only update UI objects on the main thread. This means that
you should craft a negotiation policy that allows multiple threads to communicate work
back to the main thread, which tasks the topmost activity or fragment with the work of
updating the actual UI object.

The framework provides the same Java classes and primitives to facilitate threading.
1. Thread
2. Runnable
3. Executors

Framework also provides helper classes as well.


1. AsyncTask (by default, an app pushes all of the AsyncTask objects to create a single
thread) – execute in a serial fashion
2. HandlerThread
Async Task
AsyncTask allows you to run a task on a background thread, while publishing results to
the UI thread.

AsyncTasks are killed when the activity is killed.

When an asynchronous task is executed, the task


goes through 4 steps:

1. onPreExecute() //UI thread


2. doInBackground(Params...) //background thread
3. onProgressUpdate(Progress...) //UI thread
4. onPostExecute(Result) //UI thread
Handler Thread

Using thread and updating the UI with


the help of Handler

To move data from a background thread to


the UI thread, use
a Handler that's running on the UI thread.

OR

Textview will directly put the Runnable on


MessageQueue
Tutorial Links

https://www.youtube.com/watch?v=LJ_pUlWzGsc

Explore these Network libraries:

Retrofit
Volley

You might also like