Android Developer Fundamentals V2

Slides:



Advertisements
Similar presentations
Programming with Android: Network Operations
Advertisements

SOCKET PROGRAMMING WITH MOBILE SOCKET CLIENT DEARTMENT OF COMPUTER SCIENCE IOWA STATE UNIVERSITY.
Socket Programming ENTERPRISE JAVA. 2 Content  Sockets  Streams  Threads  Readings.
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.
Network Read/Write. Review of Streams and Files java.io package InputStream and OutputStream classes for binary bytes Reader and Writer classes for characters.
1 Creating a network app Write programs that  run on different end systems and  communicate over a network.  e.g., Web: Web server software communicates.
Java Threads A tool for concurrency. OS schedules processes Ready Running 200 Blocked A process loses the CPU and another.
WECPP1 Java networking Jim Briggs based on notes by Amanda Peart based on Bell & Parr's bonus chapter
1 Networking with Java 2: The Server Side. 2 Some Terms Mentioned Last Week TCP -Relatively slow but enables reliable byte-stream transmission UDP -Fast.
System Programming Practical session 10 Java sockets.
13-Jul-15 Sockets and URLs. 2 Sockets A socket is a low-level software device for connecting two computers together Sockets can also be used to connect.
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.
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()),
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
CS378 - Mobile Computing Web - WebView and Web Services.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
Networking: Part 2 (Accessing the Internet). The UI Thread When an application is launched, the system creates a “main” UI thread responsible for handling.
 Socket  The combination of an IP address and a port number. (RFC 793 original TCP specification)  The name of the Berkeley-derived application programming.
Networking Android Club Networking AsyncTask HttpUrlConnection JSON Parser.
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.
DBI Representation and Management of Data on the Internet.
UDP vs TCP UDP Low-level, connectionless No reliability guarantee TCP Connection-oriented Not as efficient as UDP.
Practicum: - Client-Server Computing in Java Fundamental Data Structures and Algorithms Margaret Reid-Miller 13 April 2004.
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.
Introduction to Socket Programming in Android Jules White Bradley Dept. of Electrical and Computer Engineering Virginia Tech
Networks Sockets and Streams. TCP/IP in action server ports …65535 lower port numbers ( ) are reserved port echo7 time13 ftp20 telnet23.
1 cs205: engineering software university of virginia fall 2006 Network Programming* * Just enough to make you dangerous Bill Cheswick’s map of the Internet.
CS390- Unix Programming Environment CS 390 Unix Programming Environment Java Socket Programming.
Dynamic Architectures (Component Reconfiguration) with Fractal.
Android networking 1. Network programming with Android If your Android is connected to a WIFI, you can connect to servers using the usual Java API, like.
TCP/IP Protocol Stack IP Device Drivers TCPUDP Application Sockets (Gate to network) TCP: –Establish connection –Maintain connection during the communication.
UNIT-6. Basics of Networking TCP/IP Sockets Simple Client Server program Multiple clients Sending file from Server to Client Parallel search server.
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.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Adding network connections. Connecting to the Network To perform the network operations, your application manifest must include the following permissions:
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 Java API for distributed computing.
Agenda Socket Programming The OSI reference Model The OSI protocol stack Sockets Ports Java classes for sockets Input stream and.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
Network Programming. These days almost all devices.
USING ANDROID WITH THE INTERNET. Slide 2 Lecture Summary Getting network permissions Working with the HTTP protocol Sending HTTP requests Getting results.
Messaging and Networking. Objectives Send SMS messages using the Messaging app Send SMS messages programmatically from within your app Receive and consume.
Plan for today Open-Closed and Quizmaster
Threads in Java Two ways to start a thread
Network Programming in Java CS 1111 Ryan Layer May 3, 2010
Client-server Programming
NETWORK PROGRAMMING CNET 441
Networking with Java 2.
An Introduction to TCP/IP and Sockets
PRESENTED To: Sir Abid………. PRESENTED BY: Insharah khan………. SUBJECT:
Sockets and URLs 17-Sep-18.
Uniform Resource Locators
EE 422C Socket Programming
Clients and Servers 19-Nov-18.
Programming in Java Text Books :
Clients and Servers 1-Dec-18.
Networking.
Sockets and URLs 3-Dec-18.
HTTP and Sockets Lecture 6
Uniform Resource Locators (URLs)
Software Engineering for Internet Applications
CS323 Android Topics Network Basics for an Android App
Android Developer Fundamentals V2
Uniform Resource Locators
Web APIs API = Application Programmer Interface
Clients and Servers 19-Jul-19.
Clients and Servers 13-Sep-19.
Intro to Web Services Consuming the Web.
Presentation transcript:

Android Developer Fundamentals V2 Internet connection

Manage Network Connection

Required Permissions <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Getting Network information ConnectivityManager Answers queries about the state of network connectivity Notifies applications when network connectivity changes NetworkInfo Describes status of a network interface of a given type Mobile or Wi-Fi

Check if network is available ConnectivityManager connMgr = ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { text1.setText("Connected to "+networkInfo.getTypeName()); } else { text1.setText("No network connection available."); }

Check for WiFi & Mobile NetworkInfo networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); boolean isWifiConn = networkInfo.isConnected(); networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); boolean isMobileConn = networkInfo.isConnected();

Use Worker Thread AsyncTask—very short task, or no result returned to UI AsyncTaskLoader—for longer tasks, returns result to UI Background Service—later chapter Do not implement network related codes in UI thread !!

AsyncTask Only a UI thread can create and start an AsyncTask execute(): start AsyncTasks in serial context Concurrent with UI thread but sequntional with other worker threads. executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) Concurrent with UI and worker threads.

Socket Prograaming

Server Socket Using a Server Socket we can open a port and wait for incoming connections: ServerSocket listener = new ServerSocket(); listener.bind(new InetSocketAddress(InetAddress.getLocalHost(),9090)); while(true) { Socket socket = listener.accept(); publishProgress(socket); }

Client Socket Using a Client Socket we can connect to server on a specific port : Socket s= new Socket(“192.168.10.25", 7000);

Writing data to Socket We can use a StreamWriter object to write data in a socket PrintWriter out = new PrintWriter(socket.getOutputStream(), true); out.print(“Hello World”); out.flush();

Reading data from Socket We can use a StreamReader object to read data from a socket BufferedReader in; in =new BufferedReader(new InputStreamReader(socket.getInputStream())); while(socket.isConnected()) { String s=in.readLine(); if(s==null) break; publishProgress(s); } socket.close();

Special IP Addresses in Emulator 10.0.2.1 Router/gateway address 10.0.2.2 Special alias to your host loopback interface (i.e., 127.0.0.1 on your development machine) 10.0.2.3 First DNS server 10.0.2.4 / 10.0.2.5 / 10.0.2.6 Optional second, third and fourth DNS server (if any) 127.0.0.1 The emulated device loopback interface

Networking on a single Host ServerSocket ClientSocket Open port 9090 on localhost Connect to port 7000 on host (10.0.2.2) HOST Forward port 7000 to port 9090

Use adb to forwarding ports adb path: C:\Users\yourname\AppData\Local\Android\Sdk\platform-tools> adb devices : lists available emulators Forward all incoming packets to port 7000 on Host to port 9090 in emulator-5554 adb -s emulator-5554 forward tcp:7000 tcp:9090

URI

URI = Uniform Resource Identifier String that names or locates a particular resource file:// http:// and https:// content://

Sample URL for Google Books API https://www.googleapis.com/books/v1/volumes? q=pride+prejudice&maxResults=5&printType=books Constants for Parameters final String BASE_URL = "https://www.googleapis.com/books/v1/volumes?"; final String QUERY_PARAM = "q"; final String MAX_RESULTS = "maxResults"; final String PRINT_TYPE = "printType";

Build a URI for the request Uri builtURI = Uri.parse(BASE_URL).buildUpon() .appendQueryParameter(QUERY_PARAM, "pride+prejudice") .appendQueryParameter(MAX_RESULTS, "10") .appendQueryParameter(PRINT_TYPE, "books") .build(); URL requestURL = new URL(builtURI.toString());

HTTP Client Connection

Background work In the background task (for example in doInBackground()) Create URI Make HTTP Connection Download Data

How to connect to the Internet? Make a connection from scratch Use HttpURLConnection Must be done on a separate thread Requires InputStreams and try/catch blocks

Create a HttpURLConnection HttpURLConnection conn = (HttpURLConnection) requestURL.openConnection();

Configure connection conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true);

Connect and get response conn.connect(); int response = conn.getResponseCode(); InputStream is = conn.getInputStream(); String contentAsString = convertIsToString(is, len); return contentAsString;

Close connection and stream } finally { conn.disconnect(); if (is != null) { is.close(); }

Convert Response to String

Convert input stream into a string public String convertIsToString(InputStream stream, int len) throws IOException, UnsupportedEncodingException { Reader reader = null; reader = new InputStreamReader(stream, "UTF-8"); char[] buffer = new char[len]; reader.read(buffer); return new String(buffer); }

BufferedReader is more efficient StringBuilder builder = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { builder.append(line + "\n"); } if (builder.length() == 0) { return null; resultString = builder.toString();

Uploading Data setDoOutput(true) When setDoOutput is true, HttpURLConnection uses HTTP POST requests instead. Open an output stream by calling the getOutputStream() method.

HTTP Client Connection Libraries

How to connect to the Internet? Make a connection using libraries Use a third party library like OkHttp or Volley Can be called on the main thread Much less code

How to connect to the Internet? Volley RequestQueue queue = Volley.newRequestQueue(this); String url ="http://www.google.com"; StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { // Do something with response } }, new Response.ErrorListener() { public void onErrorResponse(VolleyError error) {} }); queue.add(stringRequest);

How to connect to the Internet? Volley We need to add Volley to Gradle: dependencies { ... compile 'com.android.volley:volley:1.1.1' }

OkHttp - get OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("http://publicobject.com/helloworld.txt").build(); client.newCall(request).enqueue(new Callback() { @Override public void onResponse(Call call, final Response response) throws IOException { try { String responseData = response.body().string(); JSONObject json = new JSONObject(responseData); final String owner = json.getString("name"); } catch (JSONException e) {} } });

OkHttp – get OkHttpClient client = new OkHttpClient(); String get(String url) throws IOException { Request request = new Request.Builder().url(url).build(); Response response = client.newCall(request).execute(); return response.body().string(); }

OkHttp - post public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); OkHttpClient client = new OkHttpClient(); String post(String url, String json) throws IOException { RequestBody body = RequestBody.create(JSON, json); Request request = new Request.Builder().url(url).post(body).build(); Response response = client.newCall(request).execute(); return response.body().string(); }

OkHttp - gradle compile 'com.squareup.okhttp3:okhttp:3.12.0'

Parse Results

Parsing the results Implement method to receive and handle results ( onPostExecute()) Response is often JSON or XML Parse results using helper classes JSONObject, JSONArray XMLPullParser—parses XML

JSON basics { "population":1,252,000,000, "country":"India", "cities":["New Delhi","Mumbai","Kolkata","Chennai"] }

JSONObject basics JSONObject jsonObject = new JSONObject(response); String nameOfCountry = (String) jsonObject.get("country"); long population = (Long) jsonObject.get("population"); JSONArray listOfCities = (JSONArray) jsonObject.get("cities"); Iterator<String> iterator = listOfCities.iterator(); while (iterator.hasNext()) { // do something }

Another JSON example {"menu": { "id": "file", "value": "File", "popup": { "menuitem": [ {"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"} ] } }

Another JSON example Get "onclick" value of the 3rd item in the "menuitem" array JSONObject data = new JSONObject(responseString); JSONArray menuItemArray = data.getJSONArray("menuitem"); JSONObject thirdItem = menuItemArray.getJSONObject(2); String onClick = thirdItem.getString("onclick");

END