Android Topics Asynchronous Callsbacks

Slides:



Advertisements
Similar presentations
Computer Science 320 Clumping in Parallel Java. Sequential vs Parallel Program Initial setup Execute the computation Clean up Initial setup Create a parallel.
Advertisements

USING ANDROID WITH THE INTERNET. Slide 2 Network Prerequisites The following must be included so as to allow the device to connect to the network The.
Threads, AsyncTasks & Handlers.  Android implements Java threads & concurrency classes  Conceptual view  Parallel computations running in a process.
CS220 Software Development Lecture: Multi-threading A. O’Riordan, 2009.
Cosc 4755 Phone programming: GUI Concepts & Threads.
Cosc 4730 Brief return Sockets And HttpClient And AsyncTask.
Java ThreadsGraphics Programming Graphics Programming: Java Threads.
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()),
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.
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.
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
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
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.
08 Encapsulation and Abstraction. 2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class.
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.
HW#9 Clues CSCI 571 Fall, HW#9 Prototype
(1) Introduction to Java GUIs Philip Johnson Collaborative Software Development Laboratory Information and Computer Sciences University of Hawaii Honolulu.
Recap of Part 1 Terminology Windows FormsAndroidMVP FormActivityView? ControlViewView? ?ServiceModel? Activities Views / ViewGroups Intents Services.
Java Threads 1 1 Threading and Concurrent Programming in Java Threads and Swing D.W. Denbo.
Class on Fragments & threads. Fragments fragment is a modular section of an activity, which has its own lifecycle, receives its own input events, and.
David Sutton MOBILE INTERNET. OUTLINE  This week’s app – an RSS feed reader  Mobile internet considerations  Threads (recap)  RSS feeds  Using AsyncTask.
Lecture 6: Process and Threads Topics: Process, Threads, Worker Thread, Async Task Date: Mar 1, 2016.
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.
Developing Android Services. Objectives Creating a service that runs in background Performing long-running tasks in a separate thread Performing repeated.
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
Asynchronous Task (AsyncTask) in Android
Reactive Android Development
Android Multi-Threading
Concurrency in Android
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
Singleton Pattern Command Pattern
Lecture 6: Process, Thread, Task
Lecture 28 Concurrent, Responsive GUIs
Chapter 19 Java Never Ends
CS499 – Mobile Application Development
Multithreading in Java
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Developing Android Services
Android Programming Lecture 8
CSE 154 Lecture 22: AJAX.
CS371m - Mobile Computing Responsiveness.
Multithreaded Programming
Android Topics UI Thread and Limited processing resources
Android Topics Custom ArrayAdapters Creating an Event Listener
Mobile Computing With Android ACST 4550 Android Database Storage
Android Topics Threads and the MessageQueue
Android Developer Fundamentals V2
Constructors, GUI’s(Using Swing) and ActionListner
Threads, Handlers, and AsyncTasks
Threads in Java James Brucker.
Using threads for long running tasks.
Lecture 6: Process, Thread, Task
CMSC 202 Threads.
Android Threads Dimitar Ivanov Mobile Applications with Android
Mobile Computing With Android ACST 4550 Android Animation
Presentation transcript:

Android Topics Asynchronous Callsbacks Synchronous vs Asynchronous Overview AsyncTask Explore AsyncTask documentation Basic Understanding of AsyncTask callbacks AsyncTask parameters Explore a Sample Structure of a simple AsyncTask Class Another Examlpe Rules for using AsyncTask Practice Review

Topic 1: Synchronous vs. Asynchronous Most of the code that you've written has been synchronous. Synchronous means that each line of code gets executed one right after another. Synchronous code requires us to wait for each line to finish executing before going on to the next line. Asynchronous uses callbacks to remove this sequence.

Quick look at Synchronous vs Asynchronous Waiting for something to happen (and doing nothing else until it happens!) before proceeding. Asynchronous Do something else while you’re waiting for the event to happen. When the event happens, you will get called back, and you can jump into action.

Basics of Async Callbacks in Android Asynchronous means that we tell the system we're interested in a certain event, like a click event. The system will notify us, or call us back when that event happens. In the meantime, we can go do something else in the app. This means we're not sitting around stalled or waiting. We can still do other things like scroll a list, or wait for other user input events. When the event happens, or if it even happens at all, the system will call us back and we can execute instructions that we specified.

Asynchronous callbacks is a common pattern in mobile apps.

Topic 2: OverView of AsyncTask Use an Android AsyncTask to execute some long-running code that needs to update the UI. Useful for the following: Run a specified long-running task on another thread Once this thread completes the specified task, it will perform updates to the UI.   An asynchronous task (AsyncTask) is defined by a computation that runs on a background thread and whose result is published on the UI thread.

Topic 3: Explore AsyncTask documentation Explore how to set up listeners for events. Learn how to hook into these events and be able to respond to them. http://developer.android.com/reference/android/os/AsyncTask.html What did you discover?

Basic Understanding of AsyncTask callbacks An asynchronous task is defined by 4 steps: onPreExecute, doInBackground, onProgressUpdate and onPostExecute.  

onPreExecute() Invoked on the UI thread before the task is executed. This step is normally used to setup the task.

doInBackground(Params...) invoked to perform your long-running work. The input parameters from execute are passed into this method invoked on the background thread immediately after onPreExecute() has finished executing.

onProgressUpdate(Progress...) invoked on the UI thread after a call to publishProgress(Progress...). This method is used to display any form of progress in the user interface while the background computation is still executing

onPostExecute(Result) This method is used to update the UI once the background work is completed. This callback is invoked on the UI thread. The result of the background computation is passed to this step as a parameter.

AsyncTask Parameters AsyncTask utilizes three parameters: android.os.AsyncTask<Params, Progress, Result> These parameters can be of any type.

AsyncTask Parameters The three types used by an asynchronous task are the following: Params — the type of the parameters sent to the task upon execution the type of parameters passed into execute(). Progress — the type of the progress units published during the background computation. Result — the type of the result of the background computation must be the return type of doInBackground(). Example: private class MyAsyncTask extends AsyncTask<String, Void, int > Params Progress Result

AsyncTask Parameters Not all parameters need to used by an asynchronous task. To mark a type as unused, use the type Void:   Example: private class MyTask extends AsyncTask<Void, Void, Void> { ... }

Explore the Structure of a simple AsyncTask Class

private class MyAsyncTask extends AsyncTask<X, Y, Z>   protected void onPreExecute(){ This method is executed before starting the new Thread. Use onPreExecute to initialize and setup. NOTE:The return type is void and there are no parameters. } protected Z doInBackground(X...x){ Place all the background workload in this method. doInBackground() uses a parameter of type X (array of objects from the type “X”). doInBackground() returns an object of type “Z”. protected void onProgressUpdate(Y y){ onProgressUpdate is called using the method publishProgress(y). This method is called when you want to update UI components in the Activity layout. onProgressUpdate () uses a parameter of type Y. protected void onPostExecute(Z z){ onPostExecute is called after doInBackground() has completed its work. NOTE: doInBackground() sends a value of type Z to onPostExecute().

Further Explanation of Parameters Refer to the previous slide. X : The type of the input variables value you want to set to the background process. This can be an array of objects. Y : The type of the objects you are going to enter in the onProgressUpdate method. Z : The type of the result from the operations you have done in the background process.

Another Example

Instantiating and executing an AsyncTask An AsyncTask object must be instantiated and called with the execute() method. Example:   MyAsyncTask myTask = new MyAsyncTask (); myTask.execute(x); //x is an input parameter of the type X.

new HeavyDutyTask().execute(); private class HeavyDutyTask extends AsyncTask <double, Void, int> { @Override protected void onPreExecute() { // Perform setup - runs on user interface thread }   protected int doInBackground(double…d) { // Insert heavy duty task work here! Runs in the background. protected void onProgressUpdate(Void… param) { // Update user with progress information or similar - runs on UI Thread protected void onPostExecute(int result) { // Update user interface. Runs on the UI Thread To execute this code: new HeavyDutyTask().execute();

Rules for using AsyncTask Do not call the methods onPreExecute, doInBackground and onPostExecute manually. These are callback methods and will be performed automatically done by the system.  You cannot call an AsyncTask inside another AsyncTask or Thread. The call of the method execute must be done in the UI Thread. The method onPostExecute is executed in the UI Thread (here you can call another AsyncTask!). The input parameters of the task can be an Object array, this way you can put whatever objects and types you want.

Final Review Three ways to perform work in the background: Native Threads: No Handlers Threads with Handlers (MessageQueue) AsyncTask

Native Threads (No Handlers) Pros: Android supports standard (native) Java Threads. This means that you can use native threads to execute actions in the background.   Cons: The only limitation is that you cannot directly update the UI from a background thread. If you need to update the UI from a background thread you need to use a Hander or a AsynTask.

Threads with Handlers (MessageQueue) Pros: Android supports the pairing of standard Java Threads with Handlers. Messages can be passed back to the UI Thread by using a Handler's post method. A Handler allows you to communicate back with the UI thread from a standard background thread. This is useful in android as Handler can 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 a new Handler is created, it is bound to the thread/message queue of the thread that is creating it. This method is useful for long-running heav-yduty tasks.   Cons: Requires more code and is not always useful for very short tasks that do not impact the UI.

AsyncTask Pros: The AsyncTask class encapsulates the creation of a background process and the synchronization with the UI Thread. AsyncTask is easy to use because it allows programmers to perform background operations and publish results on the UI thread without having to manipulate threads and handlers.   Cons: By default, an app pushes all of the AsyncTask objects it creates into a single thread. No always useful for very long tasks.