Android Course © 2011 University of Science – HCM City . M.Sc. Bui Tan Loc btloc@fit.hcmus.edu.vn Department of Software Engineering, Faculty of Information Technology, University of Science – Ho Chi Minh City, Viet Nam Networking with Android Android Course © 2011 University of Science – HCM City . Objectives • After completing this module, you will able to: • Send and receive data between client and server. 2 Android Course © 2011 University of Science – HCM City . Contents • Using TCP • Using UDP • Using HTTP Get Request • Using HTTP Post Request • Using HttpURLConnection • Using URLConnection 3 Android Course © 2011 University of Science – HCM City . Note • Working with Network requires the following permissions in AndroidManifest.xml: <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> 4 Android Course © 2011 University of Science – HCM City . Android SDK networking packages Package Description java.net Provides networking-related classes, including stream and datagram sockets, Internet Protocol, and generic HTTP handling. This is the multipurpose networking resource. Experienced Java developers can create applications right away with this familiar package. java.io Though not explicitly networking, it's very important. Classes in this package are used by sockets and connections provided in other Java packages. They're also used for interacting with local files (a frequent occurrence when interacting with the network). java.nio Contains classes that represent buffers of specific data types. Handy for network communications between two Java language-based end points. org.apache.* Represents a number of packages that provide fine control and functions for HTTP communications. You might recognize Apache as the popular open source Web server. 5 Android Course © 2011 University of Science – HCM City . Android SDK networking packages Package Description android.net Contains additional network access sockets beyond the core java.net.* classes. This package includes the URI class, which is used frequently in Android application development beyond traditional networking. android.net.http Contains classes for manipulating SSL certificates. android.net.wifi Contains classes for managing all aspects of WiFi (802.11 wireless Ethernet) on the Android platform. Not all devices are equipped with WiFi capability, particularly as Android makes headway in the "flip-phone" strata of cell phones from manufacturers like Motorola and LG. android.telephony.gsm Contains classes required for managing and sending SMS (text) messages. Over time, an additional package will likely be introduced to provide similar functions on non-GSM networks, such as CDMA, or something like android.telephony.cdma. 6 Android Course © 2011 University of Science – HCM City . Socket • API for applications to read and write data from TCP/IP or UDP/IP • File abstraction (open, read, write, close) • TCP: • connection-oriented protocol • monitor error-free delivery • slower than UDP • UDP: • connectionless protocol • not monitor error-free delivery • faster than TCP 7 Android Course © 2011 University of Science – HCM City . Ports • The so called well known ports are those ports in the range of 0 to 1023 only the operating system or an Administrator of the system can access these. They are used for common services such as web servers (port 80) or e-mail servers (port 25). • Registered Ports are in the range of 1024 to 49151. • Sun's NEO Object Request Broker: port numbers 1047 and 1048. • Shockwave: port number 1626. • Dynamic and/or Private Ports are those from 49152 through 65535 and are open for use without restriction. 8 Android Course © 2011 University of Science – HCM City . Getting the ip address of your phone's network private String getLocalIpAddress() { try { for (Enumeration<NetworkInterface> en = NetworkInterface .getNetworkInterfaces(); en.hasMoreElements();) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf .getInetAddresses(); enumIpAddr.hasMoreElements();) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); } } } } catch (SocketException ex) { Log.e(“DEBUG", ex.toString()); } return null; } 9 Android Course © 2011 University of Science – HCM City . Using TCP 10 [...]... References & Further readings • • • • • • Networking with Android • • http://www.ibm.com/developerworks/opensource/library/os -android -networking/ http://www.java2s.com/Code /Android/ Network/CatalogNetwork.htm Android Http Services • http://w3mentor.com/learn/category/java /android- development /android- http-services/ Android Http Access • http://www.vogella.com/articles/AndroidNetworking/article.html Socket Programming... http://www.vogella.com/articles/AndroidNetworking/article.html Socket Programming • http://www.edumobile.org /android/ android-development/socket-programming/ Socket Programming in Android Applications • http:/ /android1 0.org/index.php/articlesgeneralprogramming/262-socket-programming-in -android- applications Android Emulator as server in Socket communication • http://www.coderanch.com/t/434412 /Android/ Mobile /Android- Emulator-as-server-Socket 27 © 2011 University... HCM City Android Course Using HttpURLConnection URL url = new URL("http://www.developer .android. com"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // Get the response BufferedReader rd = new BufferedReader(new InputStreamReader( conn.getInputStream())); String line = ""; while ((line = rd.readLine()) != null) { // do something } 24 © 2011 University of Science – HCM City Android. .. URL("http://www.developer .android. com"); URLConnection conn = url.openConnection(); // Get the response BufferedReader rd = new BufferedReader(new InputStreamReader( conn.getInputStream())); String line = ""; while ((line = rd.readLine()) != null) { // do something } 25 © 2011 University of Science – HCM City Android Course Questions or Discussions 26 © 2011 University of Science – HCM City Android Course References... sb.toString(); System.out.println(page); 21 © 2011 University of Science – HCM City Android Course Using HTTP Get Request HttpClient client = new DefaultHttpClient(); HttpGet method = new HttpGet("http://w3mentor.com/download.aspx?key=valueGoesHere"); client.execute(method); 22 © 2011 University of Science – HCM City Android Course Using HTTP Post Request HttpClient client = new DefaultHttpClient();... HCM City Android Course Receiving a connection request at server-side try { ServerSocket ss = new ServerSocket(9999); while (true) { Socket server = ss.accept(); Log.d("TCP Server", "Client Connect"); // Socket is now ready to send and receive data // close connection server.close(); } } catch (IOException e) { // Write e.getMessage() to logcat } 13 © 2011 University of Science – HCM City Android Course... socket.getOutputStream(); PrintWriter pw = new PrintWriter(os, true); 14 © 2011 University of Science – HCM City Android Course Receiving data • Using BufferedReader: InputStream is = socket.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 15 © 2011 University of Science – HCM City Android Course Sending and Receiving data at server-side ServerSocket ss = new ServerSocket(9999);... client.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); output = br.readLine(); client.close(); 17 © 2011 University of Science – HCM City Android Course Using UDP 18 © 2011 University of Science – HCM City Android Course Sending and Receiving data at server-side /* Retrieve the ServerName */ InetAddress serverAddr = InetAddress.getByName(SERVERIP); /* Create new UDP-Socket... 19 © 2011 University of Science – HCM City Android Course Sending and Receiving data at client-side // Retrieve the ServerName InetAddress serverAddr = InetAddress.getByName(SERVERIP); /* Create new UDP-Socket */ DatagramSocket socket = new DatagramSocket(); /* Prepare some data to be sent */ byte[] buf = ("Hello from Client").getBytes(); /* Create UDP-packet with * data & destination(url+port) */ DatagramPacket.. .Android Course Creating a connection at client-side • Using IP Address: Socket client =new Socket("10.0.2.15", Integer.parseInt("9999")); • Using local IP Address: String ip = getLocalIpAddress(); Socket . URLConnection 3 Android Course © 2011 University of Science – HCM City . Note • Working with Network requires the following permissions in AndroidManifest.xml: <uses-permission android: name=" ;android. permission.INTERNET"/> <uses-permission. android: name=" ;android. permission.INTERNET"/> <uses-permission android: name=" ;android. permission.ACCESS_NETWORK_STATE"/> 4 Android Course © 2011 University of Science – HCM City . Android SDK networking packages Package. Engineering, Faculty of Information Technology, University of Science – Ho Chi Minh City, Viet Nam Networking with Android Android Course © 2011 University of Science – HCM City . Objectives • After completing