ODROID Multithreading in Android



Similar documents
Lecture 1 Introduction to Android

An Introduction to Android Application Development. Serdar Akın, Haluk Tüfekçi

Android Programming and Security

An Introduction to Android

An Introduction to Android. Huang Xuguang Database Lab. Inha University

Reminders. Lab opens from today. Many students want to use the extra I/O pins on

Android Development. Marc Mc Loughlin

GETTING STARTED WITH ANDROID DEVELOPMENT FOR EMBEDDED SYSTEMS

Технологии Java. Android: Введение. Кузнецов Андрей Николаевич. Санкт-Петербургский Государственный Политехнический Университет

Overview of CS 282 & Android

Android Basics. Xin Yang

Example of Standard API

Mobility Introduction Android. Duration 16 Working days Start Date 1 st Oct 2013

Introduction to Android

Introduction to Android Development. Jeff Avery CS349, Mar 2013

Chapter 2 Getting Started

ITG Software Engineering

Table of Contents. Adding Build Targets to the SDK 8 The Android Developer Tools (ADT) Plug-in for Eclipse 9

Q1. What method you should override to use Android menu system?

Running a Program on an AVD

Programming the Android Platform. Logistics

An Android-based Instant Message Application

Islamic University of Gaza. Faculty of Engineering. Computer Engineering Department. Mobile Computing ECOM Eng. Wafaa Audah.

Introduction to Android

Introduction to Android Android Architecture Software Development Purpose of the project Location Based Service (LBS) Android. Location class Google

Performance Analysis of Android Platform

Android Development. Lecture AD 0 Android SDK & Development Environment. Università degli Studi di Parma. Mobile Application Development

Mobile Application Development Android

Introduction to Android: Hello, Android! 26 Mar 2010 CMPT166 Dr. Sean Ho Trinity Western University

Università Degli Studi di Parma. Distributed Systems Group. Android Development. Lecture 1 Android SDK & Development Environment. Marco Picone

CS378 -Mobile Computing. Android Overview and Android Development Environment

Admin. Mobile Software Development Framework: Android Activity, View/ViewGroup, External Resources. Recap: TinyOS. Recap: J2ME Framework

Research and Design of Universal and Open Software Development Platform for Digital Home

Android Operating System

Android Architecture. Alexandra Harrison & Jake Saxton

Multithreading and Java Native Interface (JNI)!

Mobile Devices - An Introduction to the Android Operating Environment. Design, Architecture, and Performance Implications

Software development. Development requirements. Java. Android SDK. Eclipse IDE (optional)

A Look through the Android Stack

INTRODUCTION TO ANDROID CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 11 02/15/2011

Workshop on Android and Applications Development

MMI 2: Mobile Human- Computer Interaction Android

Last Class: OS and Computer Architecture. Last Class: OS and Computer Architecture

ANDROID PROGRAMMING - INTRODUCTION. Roberto Beraldi

ANDROID BASED MOBILE APPLICATION DEVELOPMENT and its SECURITY

Multi-core Programming System Overview

Graduate presentation for CSCI By Janakiram Vantipalli ( Janakiram.vantipalli@colorado.edu )

The Android Platform

Introduction to Android. CSG250 Wireless Networks Fall, 2008

Mobile Applications Grzegorz Budzyń Lecture. 2: Android Applications

Login with Amazon Getting Started Guide for Android. Version 2.0

Mobile Phones Operating Systems

UNIVERSITY AUTHORISED EDUCATION PARTNER (WDP)

4. The Android System

A Modular Approach to Teaching Mobile APPS Development

A Short Introduction to Android

Deep Inside Android. OpenExpo Zurich September 25 th, Gilles Printemps - Senior Architect. Copyright 2007 Esmertec AG.

ANDROID INTRODUCTION TO ANDROID

Mobile Devices - An Introduction to the Android Operating Environment. Design, Architecture, and Performance Implications

Development Techniques for Native/Hybrid Tizen Apps. Presented by Kirill Kruchinkin

Programming with Android

Introduction to Android SDK Jordi Linares

Creating and Using Databases for Android Applications

ECWM511 MOBILE APPLICATION DEVELOPMENT Lecture 1: Introduction to Android

VM Application Debugging via JTAG: Android TRACE32 JTAG Debug Bridge ADB Architecture Stop-Mode implications for ADB JTAG Transport Outlook

TUTORIALS AND QUIZ ANDROID APPLICATION SANDEEP REDDY PAKKER. B. Tech in Aurora's Engineering College, 2013 A REPORT

Understand and Build Android Programming Environment. Presented by: Che-Wei Chang

ECWM511 MOBILE APPLICATION DEVELOPMENT Lecture 1: Introduction to Android

Mobile Application Development 2014

AndroLIFT: A Tool for Android Application Life Cycles

RoverPal - A Mobile Payment Application

What else can you do with Android? Inside Android. Chris Simmonds. Embedded Linux Conference Europe Copyright 2010, 2net Limited.

1. Introduction to Android

Here to take you beyond Mobile Application development using Android Course details

Introduction to Android

Building an Android client. Rohit Nayak Talentica Software

Android Geek Night. Application framework

UI Performance Monitoring

Android Tutorial. Larry Walters OOSE Fall 2011

Android Application Development. Daniel Switkin Senior Software Engineer, Google Inc.

Android Application Development

Lab 0 (Setting up your Development Environment) Week 1

The power of root on Android emulators

Smartphone market share

HTTPS hg clone plugin library SSH hg clone plugin library

Student Attendance Through Mobile Devices

Android Developer Fundamental 1

Introduction to Android Programming (CS5248 Fall 2015)

Development. SriSeshaa Technologies. Table of Contents

Smart Shopping- An Android Based Shopping Application

Transcription:

Multithreading in Android 1

Index Android Overview Android Stack Android Development Tools Main Building Blocks(Activity Life Cycle) Threading in Android Multithreading via AsyncTask Class Multithreading via Handler -> Message Passing & Post() method Multithreading via AsyncTask Class - Deepening 2

Android Overview Awesome Ingredients: Open Source Platform o Apache/MIT License o Third party libraries rewritten Designed for Mobile Devices o Limited Memory, Battery and Speed Comprehensive platform Android is owned by Open Handset Alliance(OHA). 3

Android Stack Layers Linux Kernel Native Libraries Dalvik Runtime Application Framework 4

Linux kernel layer Why linux kernel? o Portability o Security o Features Linux kernel 2.6.x or 3.x Kernel enhancements o Drivers, Pluggable modules, Power management, IPC NativeLibraries Function Libraries o Webkit, Media framework, SQLite Bionic Libs o Optimized for embedded use:libc Native Servers o Surface flinger(manager), Audioflinger Hardware Abstraction Libraries(HAL) Android RunTime Core Libraries o Mostly JavaSE(NoAWT&Swing) o More features DalvikVM o Low memory, slow cpu, no swap space 5

ApplicationFramework Java Libraries Built for Android Services(Managers) 6

Android Development Development requirements Android SDK http://developer.android.com/sdk/index.html Eclipse IDE for Java Developers http://www.eclipse.org/downloads/packages/eclipse-classic- 372/indigosr2 Android Development Plugin http://developer.android.com/sdk/eclipse-adt.html IDE&Tools Android SDK o Class Library o Emulator and System Images o Documentation and Sample Code o Developer Tools dx Dalvik Cross - Assembler aapt Android Asset Packaging Tool adb Android Debug Bridge ddms Dalvik Debug Monitor Service Eclipse IDE + ADT plugin o UI creation easier, reduces development time Programming Languages Java C/C++(Restricted official support) http://developer.android.com/sdk/ndk/index.html 7

Android Activity Life Cycle Activity -> GUI / Window on screen Activity Life Cycle 8

Threading in Android A Thread is a concurrent unit of execution. A 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. Threads in the same VM interact and synchronize by the use of shared objects and monitors associated with these objects. There are basically two main ways of having a Thread execute application code. o One is providing a new class that extends Thread and overriding its run() method. o The other is providing a new Thread instance with a Runnable object during its creation. In both cases, the start() method must be called to actually execute the new Thread. Threads share the process' resources but are able to execute independently. Applications responsibilities can be separated o Main thread runs UI, and o Slow tasks are sent to background threads. 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. 9

Consequently, a multithreaded program operates faster on computer systems that have multiple CPUs. 10

Multithreading Via AsycTask Using the AsyncTask Class AsyncTask enables proper and easy use of the UI thread. This class allows performing background operations and publishing results on the UI thread without having to manipulate threads and/or handlers. An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined Using the AsyncTask Class 11

Multithreading Via Handler 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 o to schedule messages and runnables to be executed as some point in the future; and o to enqueuean action to be performed on a different thread than your own. Post(Runnable) & sendmessage(message) 12

Multithreading via AsyncTask Class Deepening Android application follows single thread model i.e. when android application is launched, a thread is created for running that application. This single thread model works fine for normal execution, but for the instance like network call which are usually long operations, UI hangs waiting for the response from the server. One of the methods that promptly come to our mind is to create a new thread and implements its run method for performing time consuming long operations. public void onclick(view v) { Thread t = new Thread(){ public void run(){ // Long time comsuming operation ; t.start(); The above approach of creating new thread for performing time consuming long operations would have worked fine but since Android implements single thread model and Android UI toolkit is not thread safe i.e. UI must always be updated in UI thread, updating UI view at the end of long operation may lead to some issues like UI hangs. Following are the various mechanisms provided by android via which we can access UI thread from other threads. Activity.runOnUiThread(Runnable) View.post(Runnable) 13

View.postDelayed(Runnable, long) Handler Let us look at each of them. runonuithread This activity method will run on UI thread. If the current thread is the UI thread, then the action is executed immediately. Or else the action is posted to the event queue of the UI thread. public void onclick(view v) { Thread t = new Thread(){ public void run(){ // Long time consuming operation _activity.runonuithread(new Runnable() { Operation Completed"); public void run() { _activity.setstatus("long ; t.start(); ); post & postdelayed These methods are of view and are use for updating the view. They place action (Runnable) in the message queue and this runnable action runs on UI thread. post public void onclick(view v) { // TODO Auto-generated method stub Thread t = new Thread(){ public void run() { // Long time consuming operation status.post(new Runnable() { Completed"); public void run() { status.settext("long Operstion 14

; t.start(); ); postdelayed public void onclick(view v) { // TODO Auto-generated method stub Thread t = new Thread(){ public void run() { // Long time consuming operation status.postdelayed(new Runnable() { Completed"); public void run() { status.settext("long Operstion ; t.start();, 1000); As we can see the difference between the post and postdelayed is that postdelayedaccepts one more parameter defining the delayed for the execution of action. Handler private Handler handler = new Handler() { public void handlemessage(message msg) { // Code to process the response and update UI. ; Above code snippets shows mechanism to create Handler. Here we have to override method handlemessage for Handler which accepts object of Message as paarameter. Now look at the code snippet for long operation and see how this Handler is called. 15

public void onclick(view v) { Thread t = new Thread(){ public void run(){ // Long time comsuming operation Message mymessage=new Message(); Bundle resbundle = new Bundle(); resbundle.putstring("status", "SUCCESS"); mymessage.obj=resbundle; handler.sendmessage(mymessage); ; t.start(); After the execution of long operation result is set in Message and passed to sendmessage of handler. Handler will extract the response from Message and will process and accordingly update the UI. Since Handler is part of main activity, UI thread will be responsible for updating the UI. All the above said approaches enforces creation of thread and implementing its run() method. All this make code more complex and difficult to read. To simplify this process of performing long operation and updating UI, Android introduced AsyncTask. AsyncTask With AsyncTask android takes care of thread management leaving business login writing to us. public class LongTimeConsumingOperation extends AsyncTask<String, Void, String> { protected String doinbackground(string... params) { // perform Long time consuming operation return null; protected void onpostexecute(string result) { // TODO Auto-generated method stub super.onpostexecute(result); protected void onpreexecute() { // TODO Auto-generated method stub super.onpreexecute(); 16

protected void onprogressupdate(void... values) { // TODO Auto-generated method stub super.onprogressupdate(values); For executing AsyncTask, call execute method as shown in onclick method. public void onclick(view v) { new LongTimeConsumingOperation().execute(""); Let us understand AsyncTask with the help of above example: Extend class AsyncTask and implements its methods. onpreexecute: This method is called before doinbackground method is called. doinbackground: Code to perform long operations goes here. onpostexecute: As the name suggest this method is called after doinbackground completes execution. onprogressupdate: Calling publishprogress anytime from doinbackground call this method. onpostexecute, onpreexecute and onprogressupdate is optional and need not be overridden. Also look at how we have extended LongTimeConsumingOperation withasynctask and understand AsyncTask generics. AsynTask<String, void, String> Things to note here are: 17

String represents Params i.e the type of parameter doinbackground method will accept and also represents the type of parameter execute method will accept. void represent Progress i.e the parameter type for onprogressupdate method String represents Result i.e the type of parameter accepted by onpostexecute method Rules to Remember While implementing AsyncTask we need to remember following rules: Task can be executed only once. Instance of AsyncTask needs to be created in UI thread. As shown above in onclick method a new instance of LongTimeConsumingOperation is created. execute method with parameters should be called from UI thread. Methods onpostexecute, onpreexecute and onprogressupdate should not be called explicitly. Conculsion Through AsyncTask android provides an robust way of performing task and handling UI updating. 18