ALAA M. ALSALEHI SOFTWARE ENGINEER AT IUG Multithreading in Android.

Slides:



Advertisements
Similar presentations
CE881: Mobile and Social Application Programming Simon M. Lucas Layouts.
Advertisements

13/04/2015Client-server Programming1 Block 6: Threads 1 Jin Sa.
Multi-threaded applications SE SE-2811 Dr. Mark L. Hornick 2 What SE1011 students are told… When the main() method is called, the instructions.
Threads, AsyncTasks & Handlers.  Android implements Java threads & concurrency classes  Conceptual view  Parallel computations running in a process.
Cosc 4730 Brief return Sockets And HttpClient And AsyncTask.
Threading in Java – a Tutorial QMUL IEEE SB. Why Threading When we need to run two tasks concurrently So multiple parts (>=2) of a program can run simultaneously.
HTTP and Threads. Download some code I’ve created an Android Project which gives examples of everything covered in this lecture. Download code here.here.
1 Advanced Computer Programming Concurrency Multithreaded Programs Copyright © Texas Education Agency, 2013.
Networking Nasrullah. Input stream Most clients will use input streams that read data from the file system (FileInputStream), the network (getInputStream()/getInputStream()),
UI Design Patterns & Best Practices Mike Wolfson July 22, 2010.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Concurrency in Android with.
Software Architecture of Android Yaodong Bi, Ph.D. Department of Computing Sciences University of Scranton.
Networking: Part 2 (Accessing the Internet). The UI Thread When an application is launched, the system creates a “main” UI thread responsible for handling.
1 GUI programming with threads. 2 Threads and Swing Swing is not generally thread-safe: most methods are not synchronized –correct synchronization is.
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
CS378 - Mobile Computing Responsiveness. An App Idea From Nifty Assignments Draw a picture use randomness Pick an equation at random Operators in the.
Week 3, Day 2: Threads Questions about Threads “Multithreading” in Swing Lab tomorrow: Quiz Lab 3: Threading! SE-2811 Slide design: Dr. Mark L. Hornick.
Threads II IS Outline  Quiz  Thread review  Stopping a thread  java.util.Timer  Swing threads javax.swing.Timer  ProgressMonitor.
Developing Applications with the CSI Framework A General Guide.
Android Threads. Threads Android will show an “ANR” error if a View does not return from handling an event within 5 seconds Or, if some code running in.
CSC Multiprocessor Programming, Spring, 2011 Chapter 9 – GUI Applications Dr. Dale E. Parson, week 11.
1 OS Review Processes and Threads Chi Zhang
Threads versus Events CSE451 Andrew Whitaker. This Class Threads vs. events is an ongoing debate  So, neat-and-tidy answers aren’t necessarily available.
Recap of Part 1 Terminology Windows FormsAndroidMVP FormActivityView? ControlViewView? ?ServiceModel? Activities Views / ViewGroups Intents Services.
Silberschatz, Galvin and Gagne ©2013 Operating System Concepts – 9 th Edition Chapter 4: Threads.
Multithreaded Programming in Java David Meredith Aalborg University.
Conway’s Game Of Live 1 Fall 2014 CS7020: Game Design and Development.
Java Threads 1 1 Threading and Concurrent Programming in Java Threads and Swing D.W. Denbo.
Review IS Overview: Data  Inside the application Collections  Outside the application Database XML  Getting/displaying Swing  Communicating.
Class on Fragments & threads. Fragments fragment is a modular section of an activity, which has its own lifecycle, receives its own input events, and.
Lecture 6: Process and Threads Topics: Process, Threads, Worker Thread, Async Task Date: Mar 1, 2016.
CHAPTER 6 Threads, Handlers, and Programmatic Movement.
Lec 10 agenda >git fetch origin lab10g; > git checkout -b lab10g origin/lab10g; Format/rules for Week 11 Advanced Topics (all beyond the scope of this.
USING ANDROID WITH THE INTERNET. Slide 2 Lecture Summary Getting network permissions Working with the HTTP protocol Sending HTTP requests Getting results.
Threads and Swing Multithreading. Contents I. Simulation on Inserting and Removing Items in a Combo Box II. Event Dispatch Thread III. Rules for Running.
Multithreading Chapter 6. Objectives Understand the benefits of multithreading on Android Understand multi-threading fundamentals Know the Thread class.
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.
CSC Multiprocessor Programming, Spring, 2012
CS240: Advanced Programming Concepts
CSE 486/586 Distributed Systems Android Programming --- 2
Lecture 6: Process, Thread, Task
Lecture 28 Concurrent, Responsive GUIs
Reactive Android Development
CS499 – Mobile Application Development
Threads II IS
Multithreaded Programming in Java
Android Programming Lecture 8
CS371m - Mobile Computing Responsiveness.
Android Topics UI Thread and Limited processing resources
Android Topics Asynchronous Callsbacks
Android Topics Threads and the MessageQueue
Android Developer Fundamentals V2
9. Threads SE2811 Software Component Design
Threads, Handlers, and AsyncTasks
Threads in Java James Brucker.
Using threads for long running tasks.
9. Threads SE2811 Software Component Design
Lecture 6: Process, Thread, Task
Mobile Computing Dr. Mohsin Ali Memon.
Multithreaded Programming in Java
CMSC 202 Threads.
9. Threads SE2811 Software Component Design
Android Threads Dimitar Ivanov Mobile Applications with Android
Mobile Computing With Android ACST 4550 Android Animation
Presentation transcript:

ALAA M. ALSALEHI SOFTWARE ENGINEER AT IUG Multithreading in Android

Agenda Multithreading vocabulary Main thread in android Time-consuming & blocking operations Unresponsive program Thread safety in android Message Passing is the solution Timer & Timer Task AsyncTask

Multithreading vocabulary Thread vs. process Multithreading Synchronization Thread safe Lock Design Pattern Message Passing Pattern Volatile Swing multithreading Swing utility Swing worker

Main thread All Android application components run on the main application thread  Activities, Services, and Broadcast Receivers Time-consuming Blocking operation In any component  will block all other components including Services and the visible Activity

Time-consuming & blocking operations File operations Network lookups Database transactions Complex calculations etc

Unresponsive program Android OS save himself from application does not response for input events. Unresponsive program Activities  within 5 seconds Broadcast Receivers  onReceive handlers within 10 seconds.

Unresponsive Exception

Solution Create your own thread private void doLongOperationInThread() {  (new Thread(new Runnable() {  public void run() { String result = doLongOperation();  }  })).start(); }

What about update UI from other thread? private void doLongOperationInThread() {  (new Thread(new Runnable() {  public void run() { String result = doLongOperation(); updateUI(result);  }  })).start(); }

Thread safety in android

Exception FATAL EXCEPTION: Thread-10 android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. at android.view.ViewRoot.checkThread(ViewRoot.java:2932) at android.view.ViewRoot.invalidateChild(ViewRoot.java:642) at android.view.ViewRoot.invalidateChildInParent(ViewRoot.java:668) at android.view.ViewGroup.invalidateChild(ViewGroup.java:2511) at android.view.View.invalidate(View.java:5279) at android.widget.TextView.checkForRelayout(TextView.java:5507) at android.widget.TextView.setText(TextView.java:2724) at android.widget.TextView.setText(TextView.java:2592) at android.widget.TextView.setText(TextView.java:2567) at com.modonat.threadNeed.ThreadNeedActivity.updateUI(ThreadNeedActivity.java:46) at com.modonat.threadNeed.ThreadNeedActivity.access$2(ThreadNeedActivity.java:44) at com.modonat.threadNeed.ThreadNeedActivity$2.run(ThreadNeedActivity.java:34) at java.lang.Thread.run(Thread.java:1019)

Is android UI thread-safe? Unfortunately like swing the answer will be No. Fortunately android has a good solution for this problem. Main thread who has control on UI Other thread who is doing long/blocking operatiions Create Update UI

Message Passing Android depend on message passing to solve this problem.

Handler private void updateUIByHandler() { final Handler myHandler = new Handler() public void handleMessage(Message msg) { updateUI((String) msg.obj); } }; (new Thread(new Runnable() { public void run() { Message msg = myHandler.obtainMessage();//get message object msg.obj = doLongOperation(1000); myHandler.sendMessage(msg);//send message to handle it } })).start(); }

Timer Like thread like timer in UI update. Timer timer=new Timer(); timer.schedule(new TimerTask() {  public void run() {  Message msg = myHandler.obtainMessage();  msg.obj = doLongOperation(1000);  myHandler.sendMessage(msg);} }, 1000);

AsyncTask onPreExecute  is invoked before the execution. onPostExecute  is invoked after the execution. doInBackground  the main operation. Write your heavy operation here. onProgressUpdate  Indication to the user on progress. It is invoked every time publishProgress() is called.

Refrence Android in Practice by CHARLIE COLLINS, MICHAEL D. GALPIN and MATTHIAS KÄPPLER Professional Android™ Application Development by Reto Meier Article “Android – Multithreading in a UI environment” id-multithreading-in-a-ui-environment/ id-multithreading-in-a-ui-environment/