Android Networking and Connec1vity

Similar documents
Bluetooth. Mobila applikationer och trådlösa nät HI /3/2013. Lecturer: Anders Lindström,

Communicating with a Server

CS434/534: Topics in Networked (Networking) Systems

Mobile Application (Design and) Development

App Development for Smart Devices. Lec #16: Networking

INTERFACING A SENSORY MICROCONTROLLER WITH AN ANDROID SMARTPHONE

Object-Oriented Databases Object-Relational Mappings and Frameworks. Alexandre de Spindler Department of Computer Science

Android Connectivity & Google APIs

MMI 2: Mobile Human- Computer Interaction Mobile Communication

32. And this is an example on how to retrieve the messages received through NFC.

private static String TAG = BluetoothUtils.class.getSimpleName();

M.C.A. Semester V Subject: - Mobile Computing (650003) Week : 2

10/27/17. Network Connec1on. Outline. Connect to the Internet. Connect to the Internet. Perform Network Operations. Perform Network Operations

Basics. Once socket is configured, applica6ons. Socket is an interface between applica6on and network

Socket 101 Excerpt from Network Programming

Energy Efficient Mobile Compu4ng Building low power sensing devices with Bluetooth low energy. Simo Veikkolainen Nokia May 2014

Android Tasks and Back Stack

Software Engineering Large Practical: Accessing remote data and XML parsing. Stephen Gilmore School of Informatics October 8, 2017

App Development for Smart Devices. Lec #17: Networking II

// MainActivity.java ; Noah Spenser; Senior Design; Diabetic Breathalyzer

Permissions. Lecture 18

Covers Android 2 IN ACTION SECOND EDITION. W. Frank Ableson Robi Sen Chris King MANNING

OFFLINE MODE OF ANDROID

Mobile Development Lecture 9: Android & RESTFUL Services

ANDROID SYLLABUS. Advanced Android

UNIX Sockets. COS 461 Precept 1

SMARTPHONE-CONTROLLED TOY BOAT

Bluetooth: Short-range Wireless Communication

Android App Development

Coding for Life--Battery Life, That Is

Loca%on Support in Android. COMP 355 (Muppala) Location Services and Maps 1

Android OA Android Application Engineer(R) Certifications Basic.

Mul$media Techniques in Android. Some of the informa$on in this sec$on is adapted from WiseAndroid.com

Managing network connectivity

DASH7 Alliance Protocol

Internet Technology 2/7/2013

10/7/15. MediaItem tostring Method. Objec,ves. Using booleans in if statements. Review. Javadoc Guidelines

CS378 -Mobile Computing. Services and Broadcast Receivers

CQ Beacon Android SDK V2.0.1

Lecture 17 Java Remote Method Invoca/on

SunmiPrinter Developer documentation

Android Online Training

Android Overview. Most of the material in this sec5on comes from h6p://developer.android.com/guide/

BITalino Java Application Programming Interface. Documentation Android API

Libraries are wri4en in C/C++ and compiled for the par>cular hardware.

IGEEKS TECHNOLOGIES. Software Training Division. Academic Live Projects For BE,ME,MCA,BCA and PHD Students

Assignment 2. Start: 15 October 2010 End: 29 October 2010 VSWOT. Server. Spot1 Spot2 Spot3 Spot4. WS-* Spots

Intents & Intent Filters. codeandroid.org

Kaseya Fundamentals Workshop DAY TWO. Developed by Kaseya University. Powered by IT Scholars

Networking and socket communica2on

Distributed Systems Recitation 2. Tamim Jabban

Computer Networks II Advanced Features (T )

CS5530 Mobile/Wireless Systems Android Bluetooth Interface

e-pg Pathshala Quadrant 1 e-text

Android User Interface Overview. Most of the material in this sec7on comes from h8p://developer.android.com/guide/topics/ui/index.

Sales Presenta+on OS7200 PABX. Compiled by Nicholas Naidoo for SVA Holdings (Pty) Ltd

Java Support for developing TCP Network Based Programs

By The Name of Allah. The Islamic University of Gaza Faculty of Engineering Computer Department Final Exam. Mobile Computing

Distributed Systems Recitation 2. Tamim Jabban

Politecnico di Milano Advanced Network Technologies Laboratory. ZigBee Revealed

Java Programming Unit 9. Serializa3on. Basic Networking.

Analyzing Wi Fi P2P in the context of a hangman game 1

1D/2D android secondary development

NODE.JS SERVER SIDE JAVASCRIPT. Introduc)on Node.js

Android Syllabus. Android. Android Overview and History How it all get started. Why Android is different.

User manual of STYLE WiFi Connec7on and Opera7on of imos STYLE app. (ios & Android version)

Multi Users Text Communication (with new ideas for more utilization) using Android Smartphone Bluetooth Connection

Serialisa(on, Callbacks, Remote Object Ac(va(on. CS3524 Distributed Systems Lecture 03

User manual of STYLE WiFi Connec7on and Opera7on of imos STYLE app. (ios & Android version)

Arduino meets Android Creating Applications with Bluetooth, Orientation Sensor, Servo, and LCD

Programming Environments

Lab 3. Accessing GSM Functions on an Android Smartphone

Each command-line argument is placed in the args array that is passed to the static main method as below :

ANDROID TRAINING PROGRAM COURSE CONTENT

CS 351 Design of Large Programs Sockets Example

Services. service: A background task used by an app.

Jonathan Aldrich Charlie Garrod

Tracing Bluetooth Headsets with the CATC Bluetooth Analysers

Lab 10: Sockets 12:00 PM, Apr 4, 2018

Distributed Systems 2011 Assignment 1

Index. Cambridge University Press Bluetooth Essentials for Programmers Albert S. Huang and Larry Rudolph. Index.

Characterize Energy Impact of Concurrent Network- Intensive Applica=ons on Mobile PlaAorms

Bluetooth. Bluetooth Radio

VOICE CONTROLLED ROBOT USING AN ANDROID DEVICE

Basic OS Progamming Abstrac7ons

ANDROID BASED WS SECURITY AND MVC BASED UI REPRESENTATION OF DATA

Preliminary ACTL-SLOW Design in the ACS and OPC-UA context. G. Tos? (19/04/2016)

Basic OS Progamming Abstrac2ons

Assignment 1. Start: 28 September 2015 End: 9 October Task Points Total 10


IT101. File Input and Output

Mul$media Support in Android

CS September 2017

Programming with Android: System Architecture. Dipartimento di Scienze dell Informazione Università di Bologna

Chapter 2 Applications and

Android Programming (5 Days)

Network Access Transla0on - NAT

TAMZ. JavaME. Optional APIs. Department of Computer Science VŠB-Technical University of Ostrava

Produced by. Design Patterns. MSc in Computer Science. Eamonn de Leastar

Overview. Android Apps (Partner s App) Other Partner s App Platform. Samsung Health. Server SDK. Samsung Health. Samsung Health Server

Transcription:

Android Networking and Connec1vity

Android and Networking Smartphones in general and Android in par1cular provide several means of being connected Telephony connec1ons for voice communica1on, the primary use of the smartphone Support for SMS services Connec1vity to networks and Internet through WiFi and UMTS/GPRS Bluetooth connec1vity to devices and peer- to- peer connec1ons among smartphones Let us review each of these connec1vity features briefly COMP 355 (Muppala) Networking 2

Android Telephony Basic access to informa1on about the telephony services available on the device is obtained through the TelephonyManager class telmanager = (TelephonyManager) getsystemservice(telephony_service); Use the methods of this class to determine telephony services and states: getdeviceid(), getline1number(), getnetworkoperator() etc. Register listener to receive no1fica1on of telephony state changes using the listen() method telmanager.listen(newtellistener(), PhoneStateListener.LISTEN_CALL_STATE); COMP 355 (Muppala) Networking 3

Android SMS Full access to SMS func1onality using the SMSManager class Need to set permission in the Manifest file: <uses- permission android:name= android.permission.send_sms /> Get an instance of the SMS manager: SmsManager mysms = SmsManager.getDefault(); Sending SMS messages String dest = 12345678 ; // des1na1on tel number String mess = Hello, SMS! // message mysms.sendtextmessage(dest, null, mess, null, null); Can create interes1ng applica1ons to respond to received SMS and auto respond COMP 355 (Muppala) Networking 4

Android Connec1vity Android provides the Connec1vityManager class to monitor network connec1vity state, sehng preferred network connec1ons and managing connec1vity failover Get access to the Connec1vityManager by: Connec1vityManager mynetman = (Connec1vityManager) getsystemservice(context.connectivity_service); Set permission in the Manifest file: <uses- permission android:name= android.permission.access_network_state /> Connec1vity Manager provides methods like getnetworkinfo(), getac1venetworkinfo(), and getallnetworkinfo() etc. These methods return the NetworkInfo object Can use methods within this object like isavailable(), isconnected, isconnectedorconnec1ng(), getstate(), etc. COMP 355 (Muppala) Networking 5

Android Connec1vity If you are using the network access in your applica1on, it is always a good idea to check if the network connec1vity exists, and take ac1on accordingly Example public boolean isonline() { Connec1vityManager cm = (Connec1vityManager) getsystemservice (Context.CONNECTIVITY_SERVICE); return cm.getac1venetworkinfo().isconnectedorconnec1ng(); COMP 355 (Muppala) Networking 6

Android WiFi WiFi connec1vity service provided through the WiFi manager: WifiManager wifi = (WifiManager) getsystemservice(context.wifi_service); Permissions to be set in Manifest file: <uses- permission android:name="android.permission.access_wifi_state"/ > <uses- permission android:name="android.permission.change_wifi_state"/> Enabling WiFi: if (!wifi.iswifienabledf)) if (wifi.getwifistate()!= WifiManager.WIFI_STATE_ENABLING) wifi.setwifienabled(true); WiFi Manager provides means for scanning for hotspots, crea1ng and managing WiFI network configura1ons COMP 355 (Muppala) Networking 7

Bluetooth/IEEE 802.15 Widely used connec1on technology for short- range communica1on (~ 10-100 m) Advantages: Robust, low complexity, low power consump1on (compared to WiFi), and inexpensive Works in the unlicensed 2.4 GHz band (similar to WiFi) Master- Slave configura1on (piconet) One device acts as the master All other devices connect to the master as slaves (up to 7 ac1ve slaves) Up to 255 parked (inac1ve) devices Master controls access to the communica1on channel through polling S M S P S P M P S Master device Slave device P radius of coverage P Parked device (inactive) COMP 355 (Muppala) Networking 8

Support for the Bluetooth network stack Bluetooth APIs allow applica1ons to: Scan for other Bluetooth devices Query the local Bluetooth adapter for paired Bluetooth devices Establish RFCOMM channels Connect to other devices through service discovery Transfer data to and from other devices Manage mul1ple connec1ons Supported through the android.bluetooth package Need to set permissions in Manifest file <uses- permission android:name= android.permission.bluetooth /> <uses- permission android:name= android.permission.bluetooth_admin /> Larer needed if we need to manipulate Bluetooth sehngs or ini1ate device discovery COMP 355 (Muppala) Networking 9

Four main classes in the android.bluetooth package BluetoothAdapter: represents the local bluetooth adapter; used to discover and instan1ate devices and create BluetoothServerSocket BluetoothDevice: represents the remote Bluetooth device; use BluetoothSocket to ini1ate connec1on to remote device BluetoothSocket: represents the interface for a Bluetooth socket; connec1on point allowing data exchange with another device BluetoothServerSocket: represents an open server socket to listen for incoming connec1on requests. One device needs to open a server socket for communica1on BluetoothClass: describes the general characteris1cs and capabili1es of a Bluetooth device COMP 355 (Muppala) Networking 10

To turn on Bluetooth connec1vity on your device: BluetoothAdapter mbluetoothadapter =BluetoothAdapter.getDefaultAdapter(); if (mbluetoothadapter == null) { // Device does not support Bluetooth Then enable Bluetooth: if (!mbluetoothadapter.isenabled()) { Intent enablebtintent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startac1vityforresult(enablebtintent, REQUEST_ENABLE_BT); COMP 355 (Muppala) Networking 11

Finding Bluetooth devices: Use the BluetoothAdapter class Device discovery: scan the local area for Bluetooth enabled devices, use the startdiscovery() method Returns immediately indica1ng whether discovery started successfully Discovery process takes a while: inquiry scan of about 12 sec followed by page scan of each found device Register a BroadcastReceiver for the ACTION_FOUND Intent to receive informa1on about each device discovered COMP 355 (Muppala) Networking 12

// Create a BroadcastReceiver for ACTION_FOUND private final BroadcastReceiver mreceiver = new BroadcastReceiver() { public void onreceive(context context, Intent intent) { String ac1on = intent.getac1on(); // When discovery finds a device if (BluetoothDevice.ACTION_FOUND.equals(ac1on)) { // Get the BluetoothDevice object from the Intent BluetoothDevice device = intent.getparcelableextra(bluetoothdevice.extra_device); // Add the name and address to an array adapter to show in a ListView marrayadapter.add(device.getname() + "\n" + device.getaddress()); ; // Register the BroadcastReceiver IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); registerreceiver(mreceiver, filter); // Don't forget to unregister during ondestroy COMP 355 (Muppala) Networking 13

Allowing your device to be discovered Intent discoverableintent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableintent.putextra(bluetoothadapter.extra_discoverable_d URATION, 300); startac1vity(discoverableintent); Required to make your device discoverable if you are hos1ng the server Not needed if you are ini1a1ng a connec1on COMP 355 (Muppala) Networking 14

Querying paired devices Set<BluetoothDevice> paireddevices = mbluetoothadapter.getbondeddevices(); // If there are paired devices if (paireddevices.size() > 0) { // Loop through paired devices for (BluetoothDevice device : paireddevices) { // Add the name and address to an array adapter to show in a ListView marrayadapter.add(device.getname() + "\n" + device.getaddress()); COMP 355 (Muppala) Networking 15

If you are implemen1ng an applica1on with Bluetooth for communica1on, you have to implement both the server- side and client- side mechanisms Server side opens a listening socket Client side must ini1ate the connec1on to the server Connec1on established if both server and client have a connected BluetoothSocket on the same RFCOMM channel Familiar socket programming approach Client will receive the socket when it opens an RFCOMMchannel to the server Server will receive a socket when an incoming connec1on is accepted Pairing may be ini1ated if the two devices have not been previously paired COMP 355 (Muppala) Networking 16

Server side setup: 1. Get a BluetoothServerSocket 2. Start listening for connec1on requests by calling accept() Accept() is a blocking call. Do not do it in the UI thread 3. Call close() if you wish to accept no more addi1onal connec1ons Client side setup: 1. Using the BluetoothDevice, get a BluetoothSocket 2. Ini1ate the connec1on by calling connect() COMP 355 (Muppala) Networking 17

private class AcceptThread extends Thread { private final BluetoothServerSocket mmserversocket; public AcceptThread() { // Use a temporary object that is later assigned to mmserversocket, // because mmserversocket is final BluetoothServerSocket tmp = null; try { // MY_UUID is the app's UUID string, also used by the client code tmp = mbluetoothadapter.listenusingrfcommwithservicerecord (NAME, MY_UUID); catch (IOExcep1on e) { mmserversocket = tmp; public void run() { BluetoothSocket socket = null; // Keep listening un1l excep1on occurs or a socket is returned while (true) { try { socket = mmserversocket.accept(); catch (IOExcep1on e) { break; // If a connec1on was accepted if (socket!= null) { // Do work to manage the connec1on (in a separate thread) manageconnectedsocket(socket); mmserversocket.close(); break; /** Will cancel the listening socket, and cause the thread to finish */ public void cancel() { try { mmserversocket.close(); catch (IOExcep1on e) { COMP 355 (Muppala) Networking 18

private class ConnectThread extends Thread { private final BluetoothSocket mmsocket; private final BluetoothDevice mmdevice; public ConnectThread(BluetoothDevice device) { // Use a temporary object that is later assigned to mmsocket, // because mmsocket is final BluetoothSocket tmp = null; mmdevice = device; // Get a BluetoothSocket to connect with the given BluetoothDevice try { // MY_UUID is the app's UUID string, also used by the server code tmp = device.createrfcommsockettoservicerecord(my_uuid); catch (IOExcep1on e) { mmsocket = tmp; public void run() { // Cancel discovery because it will slow down the connec1on mbluetoothadapter.canceldiscovery(); try { // Connect the device through the socket. This will block // un1l it succeeds or throws an excep1on mmsocket.connect(); catch (IOExcep1on connectexcep1on) { // Unable to connect; close the socket and get out try { mmsocket.close(); catch (IOExcep1on closeexcep1on) { return; // Do work to manage the connec1on (in a separate thread) manageconnectedsocket(mmsocket); /** Will cancel an in- progress connec1on, and close the socket */ public void cancel() { try { mmsocket.close(); catch (IOExcep1on e) { COMP 355 (Muppala) Networking 19

Once connec1on established: 1. Get the InputStream and OutputStream that handle transmissions through the soclet, via getinputstream() and getoutputstream() 2. Read and write data to the streams with read(byte[]) and write(byte[]) COMP 355 (Muppala) Networking 20

private class ConnectedThread extends Thread { private final BluetoothSocket mmsocket; private final InputStream mminstream; private final OutputStream mmoutstream; public ConnectedThread(BluetoothSocket socket) { mmsocket = socket; InputStream tmpin = null; OutputStream tmpout = null; // Get the input and output streams, using temp objects because // member streams are final try { tmpin = socket.getinputstream(); tmpout = socket.getoutputstream(); catch (IOExcep1on e) { mminstream = tmpin; mmoutstream = tmpout; public void run() { byte[] buffer = new byte[1024]; // buffer store for the stream int bytes; // bytes returned from read() // Keep listening to the InputStream un1l an excep1on occurs while (true) { try { // Read from the InputStream bytes = mminstream.read(buffer); // Send the obtained bytes to the UI Ac1vity mhandler.obtainmessage(message_read, bytes, - 1, buffer).sendtotarget(); catch (IOExcep1on e) { break; /* Call this from the main Ac1vity to send data to the remote device */ public void write(byte[] bytes) { try { mmoutstream.write(bytes); catch (IOExcep1on e) { /* Call this from the main Ac1vity to shutdown the connec1on */ public void cancel() { try { mmsocket.close(); catch (IOExcep1on e) { COMP 355 (Muppala) Networking 21

Android and HTTP Android has Apache HTTP components library built into the framework HrpClient component enables handling of HTTP requests on your behalf, issuing HTTP requests and dealing with the response You can layer a SOAP/XML- RPC layer atop this library or use it "straight" for accessing REST- style web services Android also includes three parsers for XML and a parser for JSON the tradi1onal W3C DOM parser (org.w3c.dom), a SAX parser (org.xml.sax), and the XML pull parser JSON parser (org.json) Also consider the use of third- party libraries to deal with specific formats like RSS/Atom parser COMP 355 (Muppala) Networking 22

Android and HTTP Simple usage example of HTTPGet(): HrpClient client = new DefaultHrpClient(); HrpGet request = new HrpGet(); request.seturi(new URI("hrp://www.cse.ust.hk/")); HrpResponse response = client.execute(request); in = new BufferedReader (new InputStreamReader(response.getEn1ty().getContent())); COMP 355 (Muppala) Networking 23

Android and HTTP Simple usage of HTTP Post: HrpClient hrpclient = new DefaultHrpClient(); HrpPost hrppost = new HrpPost(url); if (kvpairs!= null && kvpairs.isempty() == false) { List<NameValuePair> namevaluepairs = new ArrayList<NameValuePair>(kvPairs.size()); String k, v; Iterator<String> itkeys = kvpairs.keyset().iterator(); while (itkeys.hasnext()) { k = itkeys.next(); v = kvpairs.get(k); namevaluepairs.add(new BasicNameValuePair(k, v)); hrppost.seten1ty(new UrlEncodedFormEn1ty(nameValuePairs)); HrpResponse response; response = hrpclient.execute(hrppost); COMP 355 (Muppala) Networking 24