Multithreading Chapter 6. Objectives Understand the benefits of multithreading on Android Understand multi-threading fundamentals Know the Thread class.

Slides:



Advertisements
Similar presentations
13/04/2015Client-server Programming1 Block 6: Threads 1 Jin Sa.
Advertisements

Threads, AsyncTasks & Handlers.  Android implements Java threads & concurrency classes  Conceptual view  Parallel computations running in a process.
Intro to Threading CS221 – 4/20/09. What we’ll cover today Finish the DOTS program Introduction to threads and multi-threading.
490dp Synchronous vs. Asynchronous Invocation Robert Grimm.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
Cosc 4730 Brief return Sockets And HttpClient And AsyncTask.
1 Android: Event Handler Blocking, Android Inter-Thread, Process Communications 10/11/2012 Y. Richard Yang.
1 Advanced Computer Programming Concurrency Multithreaded Programs Copyright © Texas Education Agency, 2013.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Concurrency in Android with.
Networking: Part 2 (Accessing the Internet). The UI Thread When an application is launched, the system creates a “main” UI thread responsible for handling.
Java Programming: Advanced Topics
1 Mobile Software Development Framework: Android 2/28/2011 Y. Richard Yang.
Java Threads 11 Threading and Concurrent Programming in Java Introduction and Definitions D.W. Denbo Introduction and Definitions D.W. Denbo.
Working in the Background Radan Ganchev Astea Solutions.
Introduction to Socket Programming in Android Jules White Bradley Dept. of Electrical and Computer Engineering Virginia Tech
Concurrent Programming and Threads Threads Blocking a User Interface.
CS378 - Mobile Computing Responsiveness. An App Idea From Nifty Assignments Draw a picture use randomness Pick an equation at random Operators in the.
ALAA M. ALSALEHI SOFTWARE ENGINEER AT IUG Multithreading in Android.
SurfaceView.
Multithreading. Multitasking The multitasking is the ability of single processor to perform more than one operation at the same time Once systems allowed.
L6: Threads “the future is parallel” COMP206, Geoff Holmes and Bernhard Pfahringer.
Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8 th Edition Chapter 4: Threads.
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
Concurrent Programming in Java Based on Notes by J. Johns (based on Java in a Nutshell, Learning Java) Also Java Tutorial, Concurrent Programming in Java.
CHAPTER 6 Threads, Handlers, and Programmatic Movement.
USING ANDROID WITH THE INTERNET. Slide 2 Lecture Summary Getting network permissions Working with the HTTP protocol Sending HTTP requests Getting results.
Java Thread Programming
Chapter 4 – Thread Concepts
Chapter 3: Windows7 Part 5.
Concurrency in Android
Small talk with the UI thread
Chapter 4: Threads.
Asynchronous Task (AsyncTask) in Android
PA1 Discussion.
Advanced Topics in Concurrency and Reactive Programming: Asynchronous Programming Majeed Kassis.
Operating Systems (CS 340 D)
CS240: Advanced Programming Concepts
Chapter 4 – Thread Concepts
Activities and Intents
Lecture 21 Concurrency Introduction
Mobile Application Development Chapter 4 [Android Navigation and Interface Design] IT448-Fall 2017 IT448- Fall2017.
Lecture 28 Concurrent, Responsive GUIs
CS499 – Mobile Application Development
Operating Systems (CS 340 D)
Chapter 4: Threads.
Developing Android Services
Chapter 3: Windows7 Part 5.
Chapter 4: Threads.
12 Asynchronous Programming
Android Programming Lecture 8
Modified by H. Schulzrinne 02/15/10 Chapter 4: Threads.
Mobile Software Development Framework: Android
CS371m - Mobile Computing Responsiveness.
Multithreaded Programming
What is Concurrent Programming?
Android Topics UI Thread and Limited processing resources
Android Topics Asynchronous Callsbacks
CHAPTER 4:THreads Bashair Al-harthi OPERATING SYSTEM
Android Topics Threads and the MessageQueue
Android Developer Fundamentals V2
Chapter 4 Threads, SMP, and Microkernels
Chapter 3: Processes.
Chapter 4: Threads & Concurrency
Threads, Handlers, and AsyncTasks
Threads and Multithreading
Mobile Computing Dr. Mohsin Ali Memon.
CMSC 202 Threads.
Android Threads Dimitar Ivanov Mobile Applications with Android
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Multithreading Chapter 6

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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 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);

Lab 6-7 AsynTask Explore Pages Simulate document download Features AsyncTask ScrollView Locking screen orientation pragmatically ProgressBar 18

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

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

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

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

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

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

Lab 6-5 Art In Motion Pages Proportional motion animation Features Handler and two background threads Custom view 25

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

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