Cosc 4730 Brief return Sockets And HttpClient (and with AsyncTask) DownloadManager.

Slides:



Advertisements
Similar presentations
Chapter 6 Server-side Programming: Java Servlets
Advertisements

CS Network Programming CS 3331 Fall CS 3331 Outline Socket programming Remote method invocation (RMI)
Android Application Development A Tutorial Driven Course.
Programming with Android: Network Operations
Socket Programming ENTERPRISE JAVA. 2 Content  Sockets  Streams  Threads  Readings.
Cosc 5/4730 Android Services. What is a service? From android developer web pages: Most confusion about the Service class actually revolves around what.
A CHAT CLIENT-SERVER MODULE IN JAVA BY MAHTAB M HUSSAIN MAYANK MOHAN ISE 582 FALL 2003 PROJECT.
WECPP1 Java networking Jim Briggs based on notes by Amanda Peart based on Bell & Parr's bonus chapter
Inter Process Communication:  It is an essential aspect of process management. By allowing processes to communicate with each other: 1.We can synchronize.
System Programming Practical session 10 Java sockets.
Cosc 4730 Brief return Sockets And HttpClient And AsyncTask.
Programming with Android: Network Operations Luca Bedogni Marco Di Felice Dipartimento di Scienze dell’Informazione Università di Bologna.
Web Proxy Server. Proxy Server Introduction Returns status and error messages. Handles http CGI requests. –For more information about CGI please refer.
19-Aug-15 About the Chat program. 2 Constraints You can't have two programs (or two copies of the same program) listen to the same port on the same machine.
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.
Intro to Android Programming George Nychis Srinivasan Seshan.
CSC3170 Introduction to Database Systems
CSE 486/586 CSE 486/586 Distributed Systems PA Best Practices Steve Ko Computer Sciences and Engineering University at Buffalo.
Networking Nasrullah. Input stream Most clients will use input streams that read data from the file system (FileInputStream), the network (getInputStream()/getInputStream()),
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Concurrency in Android with.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
HTTP HTTP stands for Hypertext Transfer Protocol. It is an TCP/IP based communication protocol which is used to deliver virtually all files and other.
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 5/4730 Android Content Providers and Intents.
School of Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae, VUW Networking COMP # 21.
Cosc 5/4730 Broadcast Receiver. Broadcast receiver A broadcast receiver (short receiver) – is an Android component which allows you to register for system.
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.
Cli/Serv.: Chat/121 Client/Server Distributed Systems v Objectives –discuss a client/server based chat system –mention two other ways of chatting.
1 CSC111H Client-Server: An Introduction Dennis Burford
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
HTTP and Threads. Getting Data from the Web Believe it or not, Android apps are able to pull data from the web. Developers can download bitmaps and text.
Mr. Justin “JET” Turner CSCI 3000 – Fall 2015 CRN Section A – TR 9:30-10:45 CRN – Section B – TR 5:30-6:45.
Practicum: - Client-Server Computing in Java Fundamental Data Structures and Algorithms Margaret Reid-Miller 13 April 2004.
1 Streams Files are a computer’s long term memory Need ability for programs to –get information from files –copy information from program variables to.
Lecture 9 Network programming. Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the Internet.
Li Tak Sing COMPS311F. Case study: consumers and producers A fixed size buffer which can hold at most certain integers. A number of producers which generate.
Lab 2C Primer I/O in Java Sockets Threads More Java Stuffs.
Introduction to Socket Programming in Android Jules White Bradley Dept. of Electrical and Computer Engineering Virginia Tech
School of Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae, VUW Networking COMP # 22.
CS390- Unix Programming Environment CS 390 Unix Programming Environment Java Socket Programming.
Dynamic Architectures (Component Reconfiguration) with Fractal.
CSC 480 Software Engineering Socket. What is Socket? A socket is one end-point of a two-way communication link between two programs running on the network.
CS 4244: Internet Programming Network Programming in Java 1.0.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Java Server Programming Web Interface for Java Programs.
HW#9 Clues CSCI 571 Fall, HW#9 Prototype
1 Lecture 9: Network programming. 2 Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on.
Java Server Sockets ServerSocket : Object to listen for client connection requests Throws IOException accept() method to take the client connection. Returns.
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 Java API for distributed computing.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
World Wide Web has been created to share the text document across the world. In static web pages the requesting user has no ability to interact with the.
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.
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit9: Internet programming 1.
Object-Orientated Analysis, Design and Programming
Android Application -Architecture.
Small talk with the UI thread
Threads in Java Two ways to start a thread
Reactive Android Development
Block 15 Developing the Calculator application
Networking COMP
Client-server Programming
Android Developer Fundamentals V2
Threads, Handlers, and AsyncTasks
Clients and Servers 19-Jul-19.
Clients and Servers 13-Sep-19.
Presentation transcript:

cosc 4730 Brief return Sockets And HttpClient (and with AsyncTask) DownloadManager

Android Networking is based on standard Java SE methods – And get the BufferedReader/PrintWriter – Most Java SE network code works with almost no modifications.

typical Android network code. try { InetAddress serverAddr = InetAddress.getByName(host); //make the connection Socket socket = new Socket(serverAddr, port); String message = "Hello from Client android emulator"; try { //receive a message PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())), true); out.println(message); //send a message now BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); String str = in.readLine(); } catch(Exception e) { //error! } finally { socket.close(); in.close(); out.close(); } } catch (Exception e) { //unable to connect }

Android Client Code Making a connection, the code is pretty straight forward String hostname = “localhost”; // remote machine Int port = 3012; //remote port number //make the connection InetAddress serverAddr = InetAddress.getByName(hostname); Socket socket = new Socket(serverAddr, port); //now we have a connection to the server

Android Server Code Again pretty straight forward Int port = 3012; //this is the local port number //create the server socket ServerSocket serverSocket = new ServerSocket(port); //wait for a client to connect Socket socket = serverSocket.accept(); //now we have a connection to the client.

Reading and writing. This works for both client and server. Once we have the socket connection, we need to get the read and write part of the socket. //Write side PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter( socket.getOutputStream())),true); – Note the true, turns on autoflush. //Read side. BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

PrintWriter Networking is normally a text based protocol. – So while there are many function to send int, long, etc. I’m ignoring them. – out.print(String) and out.println(String) They both do the same thing, send a line of text. println will add an end of line marker. This is important for the read side.

BufferedReader The read method reads a single character and returns it as a int. – Second version uses a length and char[]. readLine() returns line of text as a string. It stops at the end of line marker. – Back to the print and println methods for the writer. There is a ready() methods that return true or false. True if there is a data to be read, false other. Using the read() and ready() allows to prevent blocking reads. – Example: if (in.read()) { read() } else { do something else}

Lastly. Don’t forget to close everything when you are done with the network. in.close(); out.close(); socket.close();

Android example code There is a TCPclient and TCPServ examples for the android – For the sever code you will need to tell the emulator to accept the port number – In android-sdk-windows\tools directory, run the following dos command adb forward tcp:3012 tcp:3012 – assuming you are using port 3012

Android notes You will need to put – – In the AndroidManifest.xml file At this point you should be able to use it in both the simulator and on the phone.

Last Note. You must connect your phone to UW’s UWyo wireless network to talk to a local cosc machine. – See docid=1769&parentid=1 for help. docid=1769&parentid=1

AndroidManifest.xml <manifest xmlns:android=" package="com.cosc4730.TCPclient" android:versionCode="1" android:versionName="1.0"> <activity android:name=".TCPclient"

Networking Android networking is built on standard Java SE – So use the same network code you learned earlier. – See the source code example, Android TCPclient and TCPserv for examples that run on the Android platform.

simulator For server code, you need to tell the simulator to accept the port number In android-sdk-windows\tools directory, run the following dos command – adb forward tcp:3012 tcp:3012 assuming you are using port 3012

References Android dev site of course – CN/reference/android/net/package- summary.html Socket programming tutorial. t325-s30.html

Main thread and network. Networking can take some time and should not be done on the main thread – Ie it can lock up the drawing. As of v11 (honeycomb) – It will force close if you attempt networking on the main thread. It must be done in a thread – Or a AsyncTask

HTTPCLIENT

HttpClient This is a modified version of Apache’s HttpClient – – Used a lot with the J2EE space

Use Create an HttpClient Instantiate a new HTTP method – PostMethod or GetMethod Set HTTP parameter names/values Execute the HTTP call using the HttpClient Process the HTTP response.

Example get HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(); request.setURI(new URI(" HttpResponse response = client.execute(request); To add parameters to a get HttpGet method = new HttpGet( " HttpResponse response = client.execute(method);

Example Post HttpClient client = new DefaultHttpClient(); HttpPost request = new HttpPost(" List postParameters = new ArrayList (); postParameters.add(new BasicNameValuePair("one", "valueGoesHere")); UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters); request.setEntity(formEntity); HttpResponse response = client.execute(request);

ASYNCTASK A second look.

AsyncTask Networking can’t be used on the main thread, so an AsyncTask can be ideal for short networking tasks, say file downloads or other things. – otherwise you should use threads and handlers.

AsyncTask download Example private class DownloadFilesTask extends AsyncTask { protected Long doInBackground(URL... urls) { 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)); // Escape early if cancel() is called if (isCancelled()) break; } return totalSize; } //background thread protected void onProgressUpdate(Integer... progress) { setProgressPercent(progress[0]); } //UI thread protected void onPostExecute(Long result) { showDialog("Downloaded " + result + " bytes"); } //UI thread } Once created, a task is executed very simply: new DownloadFilesTask().execute(url1, url2, url3); URL is pamaters to doInBackground Integer is the value for publishProgress and onProgressUpdate And Long is the return value and parameter to onPostExecute The call, uses URL to create the “list” used in doInBackground

Rest of the examples See the GitHub page pages for the rest of the source code for the examples. HttpClientDemo uses threads HttpClientDemo2 uses AsyncTask

DOWNLOADMANGER (API 9+)

DownloadManager The download manager is a system service that handles long-running HTTP downloads. – Clients may request that a URI be downloaded to a particular destination file. The download manager will conduct the download in the background, taking care of HTTP interactions and retrying downloads after failures or across connectivity changes and system reboots. Note that the application must have the INTERNET permission to use this class.

How it works Get the service via getSystemService DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); Make a request via the request methods DownloadManager.Request request = new DownloadManager.Request(URI) long download_id = downloadManager.enqueue(request); Setup a broadcastReciever to receive an broadcast when it’s done. – The downloadmanager uses the download_id number, so you need to store it for use in the receiver. The intent will contain the id number for the file downloaded, so you know which one (when downloading more then one at a time.)

DownloadManager.Request(URI) Request has a lot of parameters you can set –.setAllowedNetworkTypes( DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE) All networks by default – setDescription( String) – setTitle (CharSequence title) Sets the title and description for the notification line if enabled – setShowRunningNotification (boolean) Show notification, true. Deprecated for api 11+ setNotificationVisibility (int visibility) – VISIBILITY_HIDDEN, VISIBILITY_VISIBLE, VISIBILITY_VISIBLE_NOTIFY_COMPLETED. – If hidden, this requires the permission android.permission.DOWNLOAD_WITHOUT_NOTIFICATION. A note, setShowRunningNotification(false) didn’t work on 4.1.x

DownloadManager.Request(URI) (2) setDestinationInExternalFilesDir (String dirType, String subPath) – dirType is the directory type to pass to getExternalStoragePublicDirectory(String) – subPath is the path within the external directory, including the destination filename – Example: –.setDestinationInExternalPublicDir(Environment.DIRECTOR Y_DOWNLOADS, "nasapic.jpg"); allowScanningByMediaScanner () – If setting above, add this so the media scanner is called as well.

Receiver Set to receive DownloadManager.ACTION_DOWNLOAD_COMPLETE Since we don’t allows want to get download notifications, we set this on up dyanamically in onResume/OnPause IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE); registerReceiver(downloadReceiver, intentFilter); Where downloadReceiver is our method unregisterReceiver(downloadReceiver);

DownloaderManager.Query In the receiver, we deal with the query methods to find out the status of the download – Successful or failure – Based on the download_id (which we can get from the intent or keep from the enqueue method) – We filter and get a Cursor with the information

DownloaderManager.Query (2) DownloadManager.Query query = new DownloadManager.Query(); query.setFilterById(intentdownloadId); Cursor cursor = downloadManager.query(query); The example code shows you how to get the columns and information out of the cursor, including a file, so you can read the downloaded file.

Example code DownloadDemo – MainActivity has two buttons. One downloads and shows the notification, the second doesn’t – MainActivityORG stores the download_id in preferences, instead of a variable.

References (downloadManager) oid/app/DownloadManager.html oid/app/DownloadManager.html android-downloadmanager-api-opening-file- after-download android-downloadmanager-api-opening-file- after-download downloadmanager-example/ downloadmanager-example/

Q A &