Threads, Handlers, and AsyncTasks

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

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.
Cosc 4755 Phone programming: GUI Concepts & Threads.
Cosc 4730 Brief return Sockets And HttpClient And AsyncTask.
Threads II. Review A thread is a single flow of control through a program Java is multithreaded—several threads may be executing “simultaneously” If you.
1 Android: Event Handler Blocking, Android Inter-Thread, Process Communications 10/11/2012 Y. Richard Yang.
Cosc 5/4730 A little on threads and Messages: Handler class.
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.
Networking Nasrullah. Input stream Most clients will use input streams that read data from the file system (FileInputStream), the network (getInputStream()/getInputStream()),
CS378 - Mobile Computing Web - WebView and Web Services.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Concurrency in Android with.
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.
Cosc 4730 Brief return Sockets And HttpClient (and with AsyncTask) DownloadManager.
DUE Hello World on the Android Platform.
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.
Networking Android Club Networking AsyncTask HttpUrlConnection JSON Parser.
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
Address Book App 1. Define styles   Specify a background for a TextView – res/drawable/textview_border.xml.
Semaphores, Locks and Monitors By Samah Ibrahim And Dena Missak.
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
Threading Eriq Muhammad Adams J
로봇 모니터링 1/2 UNIT 20 로봇 SW 콘텐츠 교육원 조용수. 학습 목표 Message Queue Handler 2.
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.
Threads II IS Outline  Quiz  Thread review  Stopping a thread  java.util.Timer  Swing threads javax.swing.Timer  ProgressMonitor.
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.
Recap of Part 1 Terminology Windows FormsAndroidMVP FormActivityView? ControlViewView? ?ServiceModel? Activities Views / ViewGroups Intents Services.
Java: Variables and Methods By Joshua Li Created for the allAboutJavaClasses wikispace.
Topic: Junit Presenters: Govindaramanujam, Sama & Jansen, Erwin.
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.
Multithreading Chapter 6. Objectives Understand the benefits of multithreading on Android Understand multi-threading fundamentals Know the Thread class.
Concurrency in Android
CSCD 330 Network Programming
Small talk with the UI thread
Threads in Java Two ways to start a thread
Asynchronous Task (AsyncTask) in Android
Reactive Android Development
Android Multi-Threading
Concurrency in Android
CSE 501N Fall ‘09 21: Introduction to Multithreading
CS240: Advanced Programming Concepts
Notifications and Services
Java Concurrency.
Why exception handling in C++?
CS499 – Mobile Application Development
Java Concurrency.
Threads II IS
Developing Android Services
Android Programming Lecture 8
CIS 470 Mobile App Development
CS371m - Mobile Computing Responsiveness.
Threads and Multithreading
Mobile Computing With Android ACST 4550 Android Database Storage
Android Topics Asynchronous Callsbacks
Android Developer Fundamentals V2
slides created by Ethan Apter
Threads in Java James Brucker.
Service Services.
CIS 470 Mobile App Development
Using threads for long running tasks.
Cosc 4730 An Introduction.
Jim Fawcett CSE681 – SW Modeling & Analysis Fall 2018
CMSC 202 Threads.
some important concepts
Android Threads Dimitar Ivanov Mobile Applications with Android
Presentation transcript:

Threads, Handlers, and AsyncTasks Cosc 5/4730 Threads, Handlers, and AsyncTasks

Messages. Only the activity thread can change the “screen” widgets. So if you start a thread up, then you have send messages back to main thread to change a widget. And services, plus some listeners are also threads. So you need to pieces. A message handler (normally in Oncreate() ) to receive messages And a way to send those messages.

Simple messages In many cases you may only need to send a message, more like a “poke”. “Do something, you know that one!” kind of message Hander.sendEmptyMessage(int); Where the receiving side, gets a number.

Simple messages OnCreate() handler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 0) { //do whatever msg 0 is. } //check for other message as needed. Thread handler.sendEmptyMessage(0);

Message with a little information. In the handle you can get a Message object Message msg = handler.obtainMessage(); Message has a “what” like the simple message and int arg0, arg1 So you can send two pieces of integer information. Then you send that message Handler.sendMessage(msg);

information messages OnCreate() handler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 1) { int arg1 = msg.arg1; Int arg2 = msg.arg2; } //check for other message as needed. Thread Message msg = handler.obtainMessage(); //setup the message msg.what = 1; msg.arg1 = 1; msg.arg2= 3012; handler.sendMessage(msg);

Sending lots of information. Besides the two arg variables, you can set a bundle in the message as well. So if you want send more then two integer Or you want to send any other type, say strings. A quick note, you can pass a handler to another activity/fragment as well, so you can use it from other "locations" as well.

Sending lots of information OnCreate() handler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 3) { Blunde stuff = msg.getData(); str1 = stuff.getString(“key2”); … } //check for other message as needed. Thread Message msg = handler.obtainMessage(); Bundle b = new Bundle(); b.putString(“key”, “Stuff”); b.putString(“key2”, “more Stuff”); //setup the message number msg.what = 3; Msg.setData(b); //add bundle handler.sendMessage(msg);

A note on threads Pausing threads. In the Running thread If you want a running thread to “pause” and then start up again later. Use the wait and notify methods in the Thread class. In the Running thread It calls wait(); Then when the thread is to be woken up Notify is called.

Example Main thread MyThread = new Thread (this); myThread.start(); … //wake up a thread pause = false; synchronized(myThread) { //wake up 1 thread myThread.notify(); // or myThread.notifyAll() to wake up all threads. } Thread If (pause) { //boolean try { synchronized(myThread) { myThread.wait(); } } catch (InterruptedException e) { ;// failed to wait! }//end if //when notified, thread starts here. The ThreadDemo has working version of all this.

AsyncTask

AsyncTask This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers. AsyncTasks should ideally be used for short operations (a few seconds at the most.) otherwise you should use threads and handlers. A note, asyncTasks don't have a "pause" or "notify" method.

AsyncTask (2) An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute. doInBackground runs in the background. onProgressUpdate and onPostExecute are executed on the main/UI thread Meaning they can also update the widgets. The return value from doInBackground is called as parameter to onPostExecute publishProgress (called in doInBackground) invokes the onProgressUpdate

AsyncTask Example Data is information to be processed  private class processDataTask extends AsyncTask<Data, Integer, Long> {      protected Long doInBackground(Data... datas) {          int count = datas.length;          long totalSize = 0;          for (int i = 0; i < count; i++) {              //do something with the data, then publish how far along              publishProgress((int) ((i / (float) count) * 100));              // Escape early if cancel() is called              if (isCancelled()) break;          }          return totalSize; //amount of data process maybe?      } //background thread      protected void onProgressUpdate(Integer... progress) {          setProgressPercent(progress[0]); //update UI      } //UI thread      protected void onPostExecute(Long result) {          showDialog("Downloaded " + result + " bytes");      } //UI thread  } Once created, a task is executed very simply: new processDataTask().execute(Data1, Data2, Data3); Data is information to be processed Integer is the value for publishProgress and onProgressUpdate And Long is the return value and parameter to onPostExecute The call, uses Data to create the "list" So Data1, Data2, Data3 becomes an list of type Data Note, Data could be a class you created or some other collections (array/list)

Q A &