Download presentation
Presentation is loading. Please wait.
Published byBethanie Jackson Modified over 8 years ago
1
Multithreading Chapter 6
2
Objectives Understand the benefits of multithreading on Android Understand multi-threading fundamentals Know the Thread class and the Runnable interface Understand the Handler and AsyncTask classes Learn to communicate between threads 2
3
Background Android uses processes and thread management models to manage running applications, services, and the other elements of the system. When an application does several things at once, it is called multithreading (a.k.a. parallelism and concurrency). A multithreaded Android application contains two or more threads. 3
4
Multitasking: Process vs. Thread Multitasking can be subdivided into two categories: process-based multitasking and thread-based multitasking Process-based multitasking Allows a device to execute two or more programs concurrently An app is the smallest unit of code that can be dispatched by the scheduler. No shared variables and thus message-based communication (IPC) 4
5
Thread-based Multitasking A single program can consists of multiple threads to perform two or more tasks at once. Thread: the smallest unit of dispatchable code Shared variables among multiple threads Even a simple single-threaded application can benefit from parallel processing on different cores. Typically, a single thread is responsible for handling all the UI events. 5
6
Thread-based Multitasking (Cont.) Categories of operations that can be carried out on separate background threads: Heavy calculations An object’s long initialization Networking Database operations 6
7
Main vs. Background Threads Android UI framework is single threaded; a single thread is responsible for handling all the UI events of an application. Android UI threads are distinct from background threads. When an activity is created, it runs by default in the UI thread of the application. All the commands issued by the Android operating system, such as onClick, onCreate, etc., are sent to and processed by this UI thread. 7
8
Android UI Threads Application Not Responding (ANR) When a substantial amount of processing is performed on the UI thread, the application may be too busy to respond to messages sent by the Android operating system. If an application frequently computes an elaborate game move on the UI thread, the I/O operations of the system, such as processing incoming user input events, may perform sluggishly or can be blocked. 8
9
Android UI Threads When writing multithreaded applications in Android, it is a good idea to keep several things in mind about the UI thread: The UI thread should not perform tasks that take longer than a few seconds. The user interface cannot be updated from a background thread. An Android application can be entered from an Activity, Service or a Broadcast Receiver, all of which run on the UI thread. 9
10
Creating Background Threads From the main UI thread, programmers can create other threads. This is done by instantiating an object of type Thread that encapsulates a Runnable object. There are two ways in which a Runnable object can be created: 1)Extend the java.lang.Thread class 2)Implement the java.lang.Runnable interface 10
11
Runnable Interface The Runnable interface abstracts a unit of executable code. You can construct a thread on any object that implements the Runnable interface. Runnable defines only one method called run(). An application that creates an instance of Thread must provide the code that will run in that thread. 11
12
Extending the Thread Class The Thread class implements the Runnable interface public class MyThread extends Thread { public void run() { // code to be run concurrently } // start a new thread by calling the start method MyThread thread = new MyThread(); thread.start(); // Q: What happened if run is called directly? thread.run() // Q: Design pattern used? flow of control start() run() // … The method run is the concurrent unit in Java. 12
13
Implementing the Runnable Interface public class MyRunnable implements Runnable { public void run() { // code to be concurrently } // create a new thread by passing a Runnable object and start it, e.g., new Thread(new MyRunnable()).start(); // or using anonymous inner class new Thread(new Runnable() { public void run() { /* concurrent code */ } }).start(); // In Java 8 using lambda notation new Thread(() -> { /* concurrent code */ }).start() public interface Runnable { void run(); } 13
14
UI Modification from Background Threads The user interface cannot be updated from a background thread (except for synchronized methods). It has to be done on the main UI thread. Three different ways: void runOnUiThread(Runnable) of the Activity class android.os.AsyncTask class android.os.Handler class 14
15
AsyncTask In general, when performing parallel tasks running longer than a few seconds, it is best to use Java threads rather than the UI thread. AsyncTask: a convenient way to execute work units in parallel Abstract class that is designed to work with the UI Similar to a thread in that it allows background work to execute outside the UI thread Helper class for Thread and Handler, not a generic threading mechanism Not be used for long running work 15
16
AsyncTask An asynchronous process is defined by the following four steps, each implemented as a callback method void onPreExecute(): on UI thread Result doInBackground(Params…): on background thread; use publishProgress(Progress…) void onProgressUpdate(Progress…): on UI thread void onPostExecute(Result): on UI thread Once defined, an AsyncTask class is executed as: new MyAsyncTask().execute(p1, p2, p3) 16
17
17 private class DownloadFilesTask extends AsyncTask { protected Long doInBackground(URL... urls) { int count = urls.length; long totalSize = 0; for (int i = 0; i < count; i++) { totalSize += Downloader.downloadFile(urls[i]); publishProgress((int) ((i / (float) count) * 100)); if (isCancelled()) break; // terminate early if cancel() is called } return totalSize; } protected void onProgressUpdate(Integer... progress) { setProgressPercent(progress[0]); } protected void onPostExecute(Long result) { showDialog("Downloaded " + result + " bytes"); } } new DownloadFilesTask().execute(url1, url2, url3);
18
Lab 6-7 AsynTask Explore Pages 544-552 Simulate document download Features AsyncTask ScrollView Locking screen orientation pragmatically ProgressBar 18
19
Review: ProgressBar Visual indicator of progress in a given operation Default mode Indefinite/indeterminate meaning that it shows a cyclic animation Useful for tasks having no clear indication when they will be completed, e.g., sending data to web service Termination: setVisibility(int) -- not synchronized 0: View.VISIBLE; 4: View.INVISIBLE; 8: View.GONE Communication with progress bar: runOnUiThread(Runnable), Handler.post(Runnable), AsyncTask Customization Use style attribute: style="?android:attr/progressBarStyleHorizontal" Control: ProgressBar.setMax(int) -- synchronized ProgressBar.setProgress(int) -- synchronized ProgressBar.dismiss() -- synchronized 19
20
Communicating with UI Threads A Handler is part of the Android system’s framework for managing threads and is designed for inter-thread communication. It is associated with a single thread and that thread’s message queue. Two main uses To schedule messages and runnables to be executed as some point in the future To enqueue an action to be performed on a different thread. 20 M1 R1M2 Rn … MessageQueue Background Thread UI Thread
21
Basics of Handler When a handler is created for a new (background) thread, it is bound to the message queue of the thread in which it is created (the UI thread). The handler will deliver messages and runnables to this message queue and execute them as they are retrieved off the queue. Example use UI thread: Create a Handler object to expose a thread- safe message queue to the background thread. On background thread: Add either messages or runnables to the message queue through the handler. 21
22
Scheduling Runnables On UI thread: Create a handler, e.g., Handler handler = new Handler(); On background thread: Use the following methods to schedule tasks to be executed on the thread associated with a handler post(Runnable) postAtTime(Runnable, long) postDelayed(Runnable, long) E.g., handler.post(new Runnable() { … }); 22
23
Scheduling Messages On UI thread: Create a handler with a looper to handle queued messages, e.g., Handler handler = new Handler(Looper.getMainLooper()) { public void handleMessage(Message msg) { // process msg … } }); 23
24
Scheduling Messages (Cont.) On background thread: Use the following methods to post messages to the handler sendEmptyMessage(int) sendMessage(Message) sendMessageAtTime(Message, long) sendMessageDelayed(Message, long) A message object can contain a bundle of data to be processed by the Handler’s handleMessage(Message) method. 24
25
Lab 6-5 Art In Motion Pages 514-525 Proportional motion animation Features Handler and two background threads Custom view 25
26
SurfaceView Subclass of View to construct objects with a dedicated drawing surface that can be updated on a background thread Contains a rendering mechanism that allows threads to update the surface’s content without the use of a Handler Provides more resources than Views and was created with the objective of delivering a drawing surface for a background thread 26
27
Material Design New visual enhancement features introduced in Lollipop (5.0) Fluid animations Visual cues by surfaces and edges of material Use of familiar tactile attributes to help users quickly comprehend how to maneuver Application Set the android:Theme attribute in AndroidManifest.xml to Material Provide a collection of default animations for touch feedback and activity transitions 27
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.