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