1 Android: Event Handler Blocking, Android Inter-Thread, Process Communications 10/11/2012 Y. Richard Yang.

Slides:



Advertisements
Similar presentations
Cosc 5/4730 Android Services. What is a service? From android developer web pages: Most confusion about the Service class actually revolves around what.
Advertisements

All About Android Introduction to Android 1. Creating a New App “These aren’t the droids we’re looking for.” Obi-wan Kenobi 1. Bring up Eclipse. 2. Click.
Threads, AsyncTasks & Handlers.  Android implements Java threads & concurrency classes  Conceptual view  Parallel computations running in a process.
The Activity Class 1.  One application component type  Provides a visual interface for a single screen  Typically supports one thing a user can do,
Application Fundamentals. See: developer.android.com/guide/developing/building/index.html.
Threads Load new page Page is loading Browser still responds to user (can read pages in other tabs)
Android 101 Application Fundamentals January 29, 2010.
Cosc 4755 Phone programming: GUI Concepts & Threads.
Cosc 4730 Brief return Sockets And HttpClient And AsyncTask.
Mobile Programming Pertemuan 6 Presented by Mulyono Poltek NSC Surabaya.
Chien-Chung Shen Manifest and Activity Chien-Chung Shen
1 Mobile Software Development Framework: Android Activity, View/ViewGroup, External Resources, Listener 10/9/2012 Y. Richard Yang.
Android Sensors & Async Callbacks Jules White Bradley Dept. of Electrical and Computer Engineering Virginia Tech
UI Design Patterns & Best Practices Mike Wolfson July 22, 2010.
 Understanding an activity  Starting an activity  Passing information between activities  Understanding intents  Understanding the activity lifecycle.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Concurrency in Android with.
Mobile Computing Lecture#08 IntentFilters & BroadcastReceivers.
Chapter 2: Simplify! The Android User Interface
1 Mobile Software Development Framework: Android 2/23/2011 Y. Richard Yang.
Cosc 5/4730 Introduction: Threads, Android Activities, and MVC.
Networking: Part 2 (Accessing the Internet). The UI Thread When an application is launched, the system creates a “main” UI thread responsible for handling.
Rajab Davudov. Agenda Eclipse, ADT and Android SDK APK file Fundamentals – Activity – Service – Content Provider – Broadcast Receiver – Intent Hello World.
Using Intents to Broadcast Events Intents Can be used to broadcast messages anonymously Between components via the sendBroadcast method As a result Broadcast.
DUE Hello World on the Android Platform.
CS378 - Mobile Computing Intents.
16 Services and Broadcast Receivers CSNB544 Mobile Application Development Thanks to Utexas Austin.
1 Announcements Homework #2 due Feb 7 at 1:30pm Submit the entire Eclipse project in Blackboard Please fill out the when2meets when your Project Manager.
1 Mobile Software Development Framework: Android 2/28/2011 Y. Richard Yang.
1 CMSC 628: Introduction to Mobile Computing Nilanjan Banerjee Introduction to Mobile Computing University of Maryland Baltimore County
Chapter 2 The Android User Interface. Objectives  In this chapter, you learn to:  Develop a user interface using the TextView, ImageView, and Button.
Threads and Services. Background Processes One of the key differences between Android and iPhone is the ability to run things in the background on Android.
CS378 - Mobile Computing Intents. Allow us to use applications and components that are part of Android System – start activities – start services – deliver.
Android Boot Camp for Developers Using Java, Comprehensive: A Guide to Creating Your First Android Apps Chapter 2: Simplify! The Android User Interface.
Services A Service is an application component that can perform long-running operations in the background and does not provide a user interface. An application.
Applications with Multiple Activities. Most applications will have more than one activity. The main activity is started when the application is started.
1 Mobile Software Development Framework: Android Inter- Thread, Process Communications 10/11/2012 Y. Richard Yang.
Recap of Part 1 Terminology Windows FormsAndroidMVP FormActivityView? ControlViewView? ?ServiceModel? Activities Views / ViewGroups Intents Services.
Services Background operating component without a visual interface Running in the background indefinitely Differently from Activity, Service in Android.
CSE 486/586, Spring 2014 CSE 486/586 Distributed Systems Android Programming Steve Ko Computer Sciences and Engineering University at Buffalo.
Lecture 2: Android Concepts
Events. Slide 2©SoftMoore Consulting Events Events are generated when a user interacts with the view objects of an application. Examples –button clicked–
Technische Universität München Services, IPC and RPC Gökhan Yilmaz, Benedikt Brück.
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.
Mobile Programming Lecture 4 Resources, Selection, Activities, Intents.
CHAPTER 6 Threads, Handlers, and Programmatic Movement.
Services. What is a Service? A Service is not a separate process. A Service is not a thread. A Service itself is actually very simple, providing two main.
CS371m - Mobile Computing Intents 1. Allow us to use applications and components that are already part of Android System – start activities – start services.
Multithreading Chapter 6. Objectives Understand the benefits of multithreading on Android Understand multi-threading fundamentals Know the Thread class.
Concurrency in Android
CS434/534: Topics in Networked (Networking) Systems Mobile System: Android (Single App/Process) Yang (Richard) Yang Computer Science Department Yale.
Small talk with the UI thread
Lecture 2: Android Concepts
CS434/534: Topics in Networked (Networking) Systems Mobile System: Android Component Composition/ Inter-process Communication (IPC) Yang (Richard) Yang.
Android – Event Handling
Notifications and Services
Lecture 6: Process, Thread, Task
Mobile Software Development Framework: Android
Android Programming Lecture 9
Android Programming Lecture 8
Mobile Software Development Framework: Android
Android Topics UI Thread and Limited processing resources
Android Topics Asynchronous Callsbacks
Activities and Intents
Android Topics Threads and the MessageQueue
Android Developer Fundamentals V2
Threads, Handlers, and AsyncTasks
Lecture 6: Process, Thread, Task
Activities, Fragments, and Intents
CIS 470 Mobile App Development
Presentation transcript:

1 Android: Event Handler Blocking, Android Inter-Thread, Process Communications 10/11/2012 Y. Richard Yang

2 Outline r Admin r Android m Basic concepts Activity, View, External Resources, Listener m Inter-thread communications Handler, ASyncTask m Inter-process communications Intent

3 Admin. r HW2 m Due: 11:55 pm

Recap: Mobile GUI App Workflow App App lifecycle callbacks/custom -start -pause -… Display Composite Displa y Composite Displa y Display Composite Displa y Data/ Model Event Handle r Display Composite Display Composite Display

5 Recap: Android UI App Basic Concepts r Activity r View/ViewGroup m External definition of views in XML m findViewById() to reduce coupling r Link view events to event handlers m set…Listener()

Example: TipCalc Set listener: 6 public class TipCalcActivity extends Activity implements OnClickListener { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tip_calc); Button calc = (Button)findViewById(R.id.calculate); calc.setOnClickListener(this); } … }

Example: TipCalc Event Handler Handler: public void onClick(View arg0) { EditText amountText = (EditText)findViewById(R.id.amount_value); // get input from UI double amt=Double.parseDouble(amountText.getText().toString()); // compute output double tipD = amount * 0.15; // update UI String tipT = String.format("%.2f", tipD); TextView tipText = (TextView)findViewById(R.id.tip_value); tipText.setText(tipT); }

Event Handler Execution 8 r Event handler executed by the main/UI thread UI events system events message Looper UI (main) thread core/platform-frameworks-base/android/os/Looper.java.htm

Event Handler and Responsiveness 9 r Event handler blocks events in the msg queue from being processed => slow running handler leads to no UI response UI events system events message Looper UI (main) thread

Responsiveness: Numbers (Nexus One) r ~5-25 ms – uncached flash reading a byte r ~5-200+(!) ms – uncached flash writing tiny amount r ms – human perception of slow action r 108/350/500/800 ms – ping over 3G. varies! r ~1-6+ seconds – TCP setup + HTTP fetch of 6k over 3G 10

Event Handler and ANR 11 r Android system detects no response m Main thread (“event”/UI) does not respond to input in 5 sec

12 Example r play_music

13 Discussion r What are some design options if an event may take a while to be processed m Time consuming loading process, e.g., slow onCreate m Heavy computation, e.g., voice recognition, update map display m Networking access m …

14 Typical Design Guidelines r Notify user m E.g., progress bar, progress dialog m A splash screen r If possible, non-blocking, incremental update UI m E.g., gradual add items to map r Whenever possible, release UI thread ASAP m Keep event handler simple m Post heavy processing off the UI thread

Example: Background Thread r Use a background thread to do the task r Background thread behavior controlled by state r State controlled by event handler r See PlayMusicActivity 15

Service: Working in Background r Why Android Service: m Faceless components that typically run in the background the user is not directly interacting with the application). NO GUI, higher priority than inactive Activities m The system to schedule work for the service, to be run until the service or someone else explicitly stop it. r Note m A Service is not a separate process. The Service object itself does not imply it is running in its own process; unless otherwise specified, it runs in the same process as the application it is part of. m A Service is not a thread. It is not a means itself to do work off of the main thread (to avoid Application Not Responding errors). m We will cover Service more in next class.

Background Thread vs UI Thread r Problem: m Background thread and UI thread are running concurrently and may have race conditions if they modify UI simultaneously (e.g., UI switches to a different orientation) m A major sin of programming: concurrency bugs r Example: LoadingScreen 17

Example: LoadingScreen 18 public class LoadingScreen extends Activity implements Runnable public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.loading); // start a new thread to load Thread thread = new Thread(this); thread.start(); } public void run(){ longRunningTask(); setContentView(R.layout.main); } … } Conflict with UI thread

Solution r Background thread does not directly modify UI: send msg to UI thread, who processes the msg 19

Android Handler r Android’s mechanism to send and process Message and Runnable objects associated with a thread's MessageQueue.MessageMessageQueue r Each Handler instance is associated with a single thread and that thread's message queue m A handler is bound to the thread / message queue of the thread that creates it m from that point on, it will deliver messages and runnables to that message queue m That thread processes msgs 20

Android Handler 21

Using Handler: Examples r There are two main uses for a Handler m to schedule messages and runnables to be executed as some point in the future postDelayed(Runnable, delayMillis) m to enqueue an action to be performed on a different thread than your own. post(Runnable) 22

Handler public class MyActivity extends Activity { [... ] // Need handler for callbacks to the UI thread final Handler mHandler = new Handler(); // Create runnable task to give to UI thread final Runnable mUpdateResultsTask = new Runnable() { public void run() { updateResultsInUi(); } protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); [... ] } 23

Handler protected void startLongRunningOperation() { // Fire off a thread to do some work that we shouldn't do directly in the UI thread Thread t = new Thread() { public void run() { mResults = doSomethingExpensive(); mHandler.post(mUpdateResultsTask); } }; t.start(); } private void updateResultsInUi() { // Back in the UI thread -- update our UI elements based on the data in mResults [... ] } } 24

Example: Fixing LoadingScreen 25 public class LoadingScreen extends Activity implements Runnable { private Handler mHandler = new Handler(); // UI public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.loading); // start a new thread to load Thread thread = new Thread(this); thread.start(); } public void run(){ longTask(); mHandler.post(mSetFinalViewTask); } private Runnable mSetFinalViewTask = new Runnable() { public void run() { setContentView(R.layout.main); } }; } Conflict with UI thread

Example: BackgroundTimer 26

Common Pattern 27 private Handler mHandler = new Handler(); // UI handler private Runnable longTask = new Runnable() { // processing thread public void run() { while (notFinished) { // doSomething mHandler.post(taskToUpdateProgress); } // mHandler.post(taskToUpdateFinalResult) }; Thread thread = new Thread(longTask); thread.start();

AsyncTask as Abstraction 28 private class DownloadFilesTask extends AsyncTask { protected Long doInBackground(URL... urls) { // on some background thread 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)); } return totalSize; } protected void onProgressUpdate(Integer... progress) { // on UI thread! setProgressPercent(progress[0]); } protected void onPostExecute(Long result) { // on UI thread! showDialog("Downloaded " + result + " bytes"); } new DownloadFilesTask().execute(url1, url2, url3); // call from UI thread! See GoogleSearch

29

30 Outline r Admin r Android m Basic concepts Activity, View, External Resources, Listener m Inter-thread communications Handler, ASyncTask m Inter-process communications Intent, Broadcast, BroadcastReceiver, Service

31 Inter-Process Communications (IPC) r Inter-thread communications are for one activity r Inter-process communication is designed to promote the development of complex applications, by allowing developers to reuse existing data and services from other applications. r One may also use IPC for intra-app communications (e.g., between Activities of the same app)

Discussion: IPC Use Cases r One component of Android sends messages to another component of Android r An IPC message in Android is called Intent 32 Component

Target: Activity  startActivity() or startActivityForResult() to launch an activity or get an existing activity to do something new. 33 Component Activity

Target: Service  startService() to initiate a service or deliver new instructions to an ongoing service.  bindService() to establish a connection between the calling component and a target service. It can optionally initiate the service if it's not already running. 34 Component Service

Target: BroadcastReceiver  broadcastIntent() to send messages to all interested broadcast receivers. m Many kinds of broadcasts originate in system code, e.g., boot, battery low 35 Component Broadcast Receiver

Target: Data Provider  startActivityForResult() may target to a data provider (e.g., Contacts) 36 Component Data Provider

Example: A SocialApp 37

Android Application Component: Gang of Four 38

39 Outline r Admin r Android m Basic concepts Activity, View, External Resources, Listener m Inter-thread communications Handler, ASyncTask m Inter-process communications Intent

Application and Component Glues: Intent r Intent m An intent is an abstract description of an operation to be performed. Indicate operations from your own or others Component

Intent Data Structure r Primary pieces of info in an Intent m Action: The general action to be performed ACTION_VIEW, ACTION_DIAL, ACTION_EDIT, … Your own definition of strings m Data: a URI tel:123 content://contacts/people/1 hotel://name/Omni_New_Haven r Other attributes m Category m Type (MIME type) m Component (class name) m Extras (key-value store) 41 scheme host path

Intent Resolution: Explicit Intent r Explicit Intent: specifies the exact class to run 42 public class IntentController extends Activity { /** Called when the activity is first created. public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.intentcontroller); // launch tip cal button Button tipBtn = (Button) findViewById(R.id.tipButton); tipBtn.setOnClickListener(new View.OnClickListener() public void onClick(View v) { Intent tipIntent = new Intent(IntentController.this, TipCal.class); startActivity(tipIntent); } }); class name Context start activity

Explicit Intent and Manifest 43 r Make sure AndroidManifest.xml announces activities to be started <application > <activity android:name=".IntentController” android:label="IntentController" > <activity android:name=".TipCal" android:label="TipCal" > Shown in Launcher Announce class See IntentController

Explicit Intent 44 Yelp Map App Name: MapActivity To: MapActivity Only the specified destination receives this message