Thread. A Thread is a concurrent unit of execution. The thread has its own call stack for methods being invoked, their arguments and local variables.

Similar documents
shared objects monitors run() Runnable start()

Create a local SQL database hosting a CUSTOMER table. Each customer includes [id, name, phone]. Do the work inside Threads and Asynctasks.

Android Services. Victor Matos Cleveland State University. Services

Embedded Systems Programming - PA8001

Android Data Storage

Vienos veiklos būsena. Theory

Mobile Application Development Lab [] Simple Android Application for Native Calculator. To develop a Simple Android Application for Native Calculator.

Basic GUI elements - exercises

INTRODUCTION TO ANDROID

Mobile Programming Practice Background processing AsynTask Service Broadcast receiver Lab #5

ANDROID APPS DEVELOPMENT FOR MOBILE AND TABLET DEVICE (LEVEL I)

Simple Currency Converter

COMP4521 EMBEDDED SYSTEMS SOFTWARE

ANDROID APPS DEVELOPMENT FOR MOBILE AND TABLET DEVICE (LEVEL I)

IPN-ESCOM Application Development for Mobile Devices. Extraordinary. A Web service, invoking the SOAP protocol, in an Android application.

Android Apps Development for Mobile and Tablet Device (Level I) Lesson 2

EMBEDDED SYSTEMS PROGRAMMING Application Tip: Saving State

Diving into Android. By Jeroen Tietema. Jeroen Tietema,

<uses-permission android:name="android.permission.internet"/>

Database Development In Android Applications

Saving application preferences

Software Practice 3 Today s lecture Today s Task

Lesson 9. Android's Concurrency. Android's Concurrency Mechanisms... 3

Unit 4. Thread class & Runnable Interface. Inter Thread Communication

Multithreading and Interactive Programs

Manifest.xml. Activity.java

TextView. A label is called a TextView. TextViews are typically used to display a caption TextViews are not editable, therefore they take no input

Android Workshop: Model View Controller ( MVC):

CHAPTER 15 ASYNCHRONOUS TASKS

else if(rb2.ischecked()) {

Tip Calculator. xmlns:tools=" android:layout_width="match_parent"

Real-Time Embedded Systems

Embedded Systems Programming - PA8001

Produced by. Design Patterns. MSc in Computer Science. Eamonn de Leastar

EMBEDDED SYSTEMS PROGRAMMING Application Basics

MAD ASSIGNMENT NO 2. Submitted by: Rehan Asghar BSSE AUGUST 25, SUBMITTED TO: SIR WAQAS ASGHAR Superior CS&IT Dept.

EMBEDDED SYSTEMS PROGRAMMING Application Tip: Managing Screen Orientation

Meniu. Create a project:

Hydrogen Car Mobile Display

CSE 660 Lab 7. Submitted by: Arumugam Thendramil Pavai. 1)Simple Remote Calculator. Server is created using ServerSocket class of java. Server.

Chapter 5 Flashing Neon FrameLayout

Mobile and Ubiquitous Computing: Android Programming (part 4)

Android Basics. Android UI Architecture. Android UI 1

M.A.D Assignment # 1

EMBEDDED SYSTEMS PROGRAMMING UI Specification: Approaches

App Development for Smart Devices. Lec #7: Audio, Video & Telephony Try It Out

CS 351 Design of Large Programs Threads and Concurrency

Android Beginners Workshop

Mobila applikationer och trådlösa nät, HI1033, HT2012

Arrays of Buttons. Inside Android

Notification mechanism

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

EMBEDDED SYSTEMS PROGRAMMING Android Services

Android Activities. Akhilesh Tyagi

ITU- FAO- DOA- TRCSL. Training on. Innovation & Application Development for E- Agriculture. Shared Preferences

Mobile Programming Lecture 5. Composite Views, Activities, Intents and Filters

Figure 2.10 demonstrates the creation of a new project named Chapter2 using the wizard.

Android Specifics. Jonathan Diehl (Informatik 10) Hendrik Thüs (Informatik 9)

Practical 1.ListView example

Android HelloWorld - Example. Tushar B. Kute,

Android for Java Developers Dr. Markus Schmall, Jochen Hiller

UNDERSTANDING ACTIVITIES

CS371m - Mobile Computing. Responsiveness

Threads. Definitions. Process Creation. Process. Thread Example. Thread. From Volume II

Services. Marco Ronchetti Università degli Studi di Trento

Services. service: A background task used by an app.

Theme 2 Program Design. MVC and MVP

PENGEMBANGAN APLIKASI PERANGKAT BERGERAK (MOBILE)

Mobile User Interfaces

Unit - IV Multi-Threading

CSE 660 Lab 3 Khoi Pham Thanh Ho April 19 th, 2015

Action Bar. (c) 2010 Haim Michael. All Rights Reserv ed.

COMP4521 EMBEDDED SYSTEMS SOFTWARE

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007

Solving an Android Threading Problem

Intents. Your first app assignment

Android. Broadcasts Services Notifications

Understand applications and their components. activity service broadcast receiver content provider intent AndroidManifest.xml

Getting started: Installing IDE and SDK. Marco Ronchetti Università degli Studi di Trento

Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit

Software Practice 1 - Multithreading

CMSC 433 Programming Language Technologies and Paradigms. Concurrency

Create Parent Activity and pass its information to Child Activity using Intents.

Adaptation of materials: dr Tomasz Xięski. Based on presentations made available by Victor Matos, Cleveland State University.

Interface ใน View class ประกอบด วย

EMBEDDED SYSTEMS PROGRAMMING Application Tip: Switching UIs

10.1 Introduction. Higher Level Processing. Word Recogniton Model. Text Output. Voice Signals. Spoken Words. Syntax, Semantics, Pragmatics

1D/2D android secondary development

Contribution:javaMultithreading Multithreading Prof. Dr. Ralf Lämmel Universität Koblenz-Landau Software Languages Team

Tłumaczenie i adaptacja materiałów: dr Tomasz Xięski. Na podstawie prezentacji udostępnionych przez Victor Matos, Cleveland State University.

Overview. What are layouts Creating and using layouts Common layouts and examples Layout parameters Types of views Event listeners

7. MULTITHREDED PROGRAMMING

android-espresso #androidespresso

Communicating with a Server

Mobila applikationer och trådlösa nät, HI1033, HT2013

Android UI: Overview

Android Basics. - Bhaumik Shukla Android Application STEALTH FLASH

Have a development environment in 256 or 255 Be familiar with the application lifecycle

App Development for Smart Devices. Lec #18: Advanced Topics

Creating a Custom ListView

Transcription:

1

Thread A Thread is a concurrent unit of execution. The thread has its own call stack for methods being invoked, their arguments and local variables. Each virtual machine instance has at least one main Thread running when it is started; typically, there are several others for housekeeping. The application might decide to launch additional Threads for specific purposes. 2

Creating Threads (method 1) extending the Thread class must implement the run() method thread ends when run() method finishes call.start() to get the thread ready to run

Creating Threads (method 2) Create thread by implementing Runnable interface: The simplest way to make a thread is to make a class that implements the runnable interface. To implement the runnable, a class require only implement a single method called 'run( )', which is declared as following : public void run( ) After you make a class that implements 'Runnable', you will instantiate an Object of type 'Thread' from within that class. The thread defines various constructors. The one that we shall use is representing here: Thread(Runnable threadobj, String threadname); After the new thread is made, it will not start running until you call it 'start( )' method, which is declared within the Thread. The 'start( )' method is representing here: void start( );

Thread State Thread State 5

Multithreading A multithreading is a specialized form of multitasking. Multithreading requires less overhead than multitasking processing. 6

Advantages of Multi-Threading Threads share the process' resources but are able to execute independently. Applications responsibilities can be separated main thread runs UI, and slow tasks are sent to background threads. Threading provides an useful abstraction of concurrent execution. Particularly useful in the case of a single process that spawns multiple threads on top of a multiprocessor system. In this case real parallelism is achieved. Consequently, a multithreaded program operates faster on computer systems that have multiple CPUs. 7

Disadvantages of Multi-Threading Code tends to be more complex Need to detect, avoid, resolve deadlocks Android's Approach to Slow Activities An application may involve a time-consuming operation, however we want the UI to be responsive to the user. Android offers two ways for dealing with This scenario: 1. Do expensive operations in a background service, using notifications to inform users about next step 2. Do the slow work in a background thread. Interaction between Android threads is accomplished using (a) Handler objects and (b) posting Runnable objects to the main view. 8

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 9

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

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. 11

Unresponsive Exception 12

Inter-Thread Communication 13

Looper and Handler 14

Looper Wrapper class to attach a message queue to a thread and manage this queue Threads by default do not have a message loop associated with them To create one, call prepare() in the thread that is to run the loop, and then loop() to have it process messages until the loop is stopped The main thread (a.k.a. UI thread) in an Android application sets up as a looper thread before your application is created. Most interaction with a message loop is through the Handler class. 15

Handler A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue. http://developer.android.com/reference/android/os/handler.html 16

Processing Messages To process messages sent by the background threads, your Handler needs to implement the listener handlemessage(... ) which will be called with each message that appears on the message queue. There, the handler can update the UI as needed. However, it should still do that work quickly, as other UI work is suspended until the Handler is done. 17

Send Message to MessageQueue A secondary thread that wants to communicate with the main thread must request a message token using the obtainmessage() method. There are a few forms of obtainmessage(), allowing you to just create an empty Message object, or messages holding arguments Example // thread 1 produces some local data String localdata = "Greeting from thread 1"; // thread 1 requests a message & adds localdata to it Message mgs = myhandler.obtainmessage (1, localdata); Once obtained, the background thread can fill data into the message token and attach it to the Handler's message queue using the sendmessage() method. 18

Multi-Threading Using Post 19

Multi-Threading Using Post 20

Messages To send a Message to a Handler, the thread must first invoke obtainmessage() to get the Message object out of the pool. There are a few forms of obtainmessage(), allowing you to just create an empty Message object, or messages holding arguments Example // thread 1 produces some local data String localdata = "Greeting from thread 1"; // thread 1 requests a message & adds localdata to it Message mgs = myhandler.obtainmessage (1, localdata); 21

sendmessage Methods You deliver the message using one of the sendmessage...() family of methods, such as sendmessage() puts the message at the end of the queue immediately sendmessageatfrontofqueue() puts the message at the front of the queue immediately (versus the back, as is the default), so your message takes priority over all others sendmessageattime() puts the message on the queue at the stated time, expressed in the form of milliseconds based on system uptime (SystemClock.uptimeMillis()) sendmessagedelayed() puts the message on the queue after a delay, expressed in milliseconds 22

Example 1. Progress Bar - Using Message Passing The main thread displays a horizontal and a circular progress bar widget showing the progress of a slow background operation. Some random data is periodically sent from the background thread and the messages are displayed in the main view. <?xml version="1.0" encoding="utf-8"?> <LinearLayout android:id="@+id/widget28" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#ff009999" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android" > <TextView android:id="@+id/textview01" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="working..." android:textsize="18sp" android:textstyle="bold" /> <ProgressBar android:id="@+id/progress" android:layout_width="fill_parent" android:layout_height="wrap_content" style="?android:attr/progressbarstylehorizontal" /> <ProgressBar android:id="@+id/progress2" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/textview02" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="returned from thread..." android:textsize="14sp" android:background="#ff0000ff" android:textstyle="bold" android:layout_margin="7px"/> </LinearLayout> 23

Multi-Threading Progress Bar Using Message Passing import java.util.random; import android.app.activity; import android.os.bundle; import android.os.handler; import android.os.message; import android.view.view; import android.widget.progressbar; import android.widget.textview; public class ThreadDemo1ProgressBar extends Activity { ProgressBar bar1; ProgressBar bar2; TextView msgworking; TextView msgreturned; boolean isrunning = false; final int MAX_SEC = 60; // (seconds) lifetime for background thread String strtest = "global value seen by all threads "; int inttest = 0; 24

Multi-Threading Progress Bar Using Message Passing Handler handler = new Handler() { @Override public void handlemessage(message msg) { String returnedvalue = (String)msg.obj; //do something with the value sent by the background thread here... msgreturned.settext("returned by background thread: \n\n" + returnedvalue); bar1.incrementprogressby(2); //testing thread's termination if (bar1.getprogress() == MAX_SEC){ msgreturned.settext("done \n back thread has been stopped"); isrunning = false; if (bar1.getprogress() == bar1.getmax()){ msgworking.settext("done"); bar1.setvisibility(view.invisible); bar2.setvisibility(view.invisible); bar1.getlayoutparams().height = 0; bar2.getlayoutparams().height = 0; else { msgworking.settext("working..." + bar1.getprogress() ); ; //handler 25

Progress Bar Using Message Passing @Override public void oncreate(bundle icicle) { super.oncreate(icicle); setcontentview(r.layout.main); bar1 = (ProgressBar) findviewbyid(r.id.progress); bar2 = (ProgressBar) findviewbyid(r.id.progress2); bar1.setmax(max_sec); bar1.setprogress(0); msgworking = (TextView)findViewById(R.id.TextView01); msgreturned = (TextView)findViewById(R.id.TextView02); strtest += "-01"; // slightly change the global string inttest = 1; Multi-Threading //oncreate public void onstop() { super.onstop(); isrunning = false; 26

public void onstart() { super.onstart(); // bar1.setprogress(0); Thread background = new Thread(new Runnable() { public void run() { try { for (int i = 0; i < MAX_SEC && isrunning; i++) { //try a Toast method here (will not work!) //fake busy busy work here Thread.sleep(1000); //one second at a time Random rnd = new Random(); Multi-Threading // this is a locally generated value String data = "Thread Value: " + (int) rnd.nextint(101); //we can see and change (global) class variables data += "\n" + strtest + " " + inttest; inttest++; //request a message token and put some data in it Message msg = handler.obtainmessage(1, (String)data); // if thread is still alive send the message if (isrunning) { handler.sendmessage(msg); catch (Throwable t) { // just end the background thread //run );//background isrunning = true; background.start(); //onstart //class 27

28

AsyncTask The AsyncTask class encapsulates the creation of Threads and Handlers. To use AsyncTask you must subclass it. AsyncTask uses generics and varargs. The parameters are the following AsyncTask <TypeOfVarArg Params, ProgressValue, ResultValue> AsyncTask has four steps: onpreexecute ( Invoked on UI Thread) is invoked before the execution. doinbackground (Invoked on background Thread) the main operation. Write your heavy operation here. onpostexecute (Invoked on UI Thread) is invoked after the execution. onprogressupdate (Invoked on UI Thread) Indication to the user on progress. It is invoked every time publishprogress() is called. 29

AsyncTask An AsyncTask is started via the execute() method. The execute() method calls the doinbackground() and the onpostexecute() method. The doinbackground() method contains the coding instruction which should be performed in a background thread. This method runs automatically in a separate Thread. The onpostexecute() method synchronizes itself again with the user interface thread and allows it to be updated. This method is called by the framework once the doinbackground() method finishes. 30

AsyncTask - Example public class Main extends Activity { Button btnslowwork; Button btnquickwork; EditText etmsg; Long startingmillis; @Override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); etmsg = (EditText) findviewbyid(r.id.edittext01); btnslowwork = (Button) findviewbyid(r.id.button01); // slow work...for example: delete all data from a database or get data from Internet this.btnslowwork.setonclicklistener(new OnClickListener() { public void onclick(final View v) { new VerySlowTask().execute(); ); btnquickwork = (Button) findviewbyid(r.id.button02); // delete all data from database (when delete button is clicked) this.btnquickwork.setonclicklistener(new OnClickListener() { public void onclick(final View v) { etmsg.settext((new Date()).toLocaleString()); ); // oncreate 31

AsyncTask - Example private class VerySlowTask extends AsyncTask <String, Long, Void> { private final ProgressDialog dialog = new ProgressDialog(Main.this); // can use UI thread here protected void onpreexecute() { startingmillis = System.currentTimeMillis(); etmsg.settext("start Time: " + startingmillis); this.dialog.setmessage("wait\nsome SLOW job is being done..."); this.dialog.show(); // automatically done on worker thread (separate from UI thread) protected Void doinbackground(final String... args) { try { // simulate here the slow activity for (Long i = 0L; i < 3L; i++) { Thread.sleep(2000); publishprogress((long)i); catch (InterruptedException e) { Log.v("slow-job interrupted", e.getmessage()) return null; 32

AsyncTask - Example // periodic updates - it is OK to change UI @Override protected void onprogressupdate(long... value) { super.onprogressupdate(value); etmsg.append("\nworking..." + value[0]); // can use UI thread here protected void onpostexecute(final Void unused) { if (this.dialog.isshowing()) { this.dialog.dismiss(); // cleaning-up, all done etmsg.append("\nend Time: + (System.currentTimeMillis()-startingMillis)/1000); etmsg.append("\ndone!"); //AsyncTask // Main 33