Wireless Networking with Android

Slides:



Advertisements
Similar presentations
Bluetooth. Wireless networking technology Limited broadcast range (< 10 meters) Example uses include Connecting headsets to phones, keyboard/mouse to.
Advertisements

1 Working with the Bluetooth radio Nilanjan Banerjee Mobile Systems Programming University of Arkansas Fayetteville, AR
WiFi in Android.
Remote Procedure Call (RPC)
Cosc 4/5730 Android and Blackberry Near Field Communications (NFC)
Wireless Networking with Android Uichin Lee KAIST KSE.
1 Java Networking – Part I CS , Spring 2008/9.
Inter Process Communication:  It is an essential aspect of process management. By allowing processes to communicate with each other: 1.We can synchronize.
Fundamentals of Python: From First Programs Through Data Structures
Cosc 5/4730 Android Bluetooth. Bluetooth Basics First off Bluetooth is NOT – Infrared, which requires line-of-sight – a/b/g/n. It was designed as.
Bluetooth. Bluetooth is an open, wireless protocol for exchanging data between devices over a short distance. –managed by the Bluetooth Special Interest.
CEG3185 Tutorial 4 Prepared by Zhenxia Zhang Revised by Jiying Zhao (2015w)
NFC.  Near Filed Communication  Is a short range high frequency wireless communication technology  Low speed (106 to 424 kbps)  Low friction setup.
CS378 - Mobile Computing Connecting Devices. How to pass data between devices? – Chat – Games – Driving Options: – Use the cloud and a service such as.
Ch. 5 – Access Points. Overview Access Point Connection.
Hacking the Bluetooth Pairing Authentication Process Graduate Operating System Mini Project Siyuan Jiang and Haipeng Cai.
CS378 - Mobile Computing What's Next?. Fragments Added in Android 3.0, a release aimed at tablets A fragment is a portion of the UI in an Activity multiple.
Distributed systems – Part 2  Bluetooth – 2 nd set of slides Anila Mjeda.
© Keren Kalif Intro to Android Development Written by Keren Kalif, Edited by Liron Blecher Contains slides from Google I/O presentation.
Mobile Application Development Selected Topics – CPIT 490
ECE 424 Embedded Systems Design Networking Connectivity Chapter 12 Ning Weng.
© 2008, Renesas Technology America, Inc. All Rights Reserved The RCAN-ET peripheral and the CAN API SH2 & SH2A MCUs V 1.2 Mar 2010.
Software Architecture of Android Yaodong Bi, Ph.D. Department of Computing Sciences University of Scranton.
CSS216 MOBILE PROGRAMMING Android, Chapter 13 Book: “Professional Android™ 2 Application Development” by Reto Meier, 2010 by: Andrey Bogdanchikov (
Common Devices Used In Computer Networks
Google Cloud Messaging for Android (GCM) is a free service that helps developers send data from servers to their Android.
– Chapter 5 – Secure LAN Switching
Network Security1 – Chapter 5 – Secure LAN Switching Layer 2 security –Port security –IP permit lists –Protocol filtering –Controlling LAN floods (using.
Cosc 5/4730 Broadcast Receiver. Broadcast receiver A broadcast receiver (short receiver) – is an Android component which allows you to register for system.
CS378 - Mobile Computing Intents.
16 Services and Broadcast Receivers CSNB544 Mobile Application Development Thanks to Utexas Austin.
1-1 Embedded Network Interface (ENI) API Concepts Shared RAM vs. FIFO modes ENI API’s.
© Aastra – 2012 SIP-DECT 4.0 RFP 43 WLAN June 2012.
1. Insert the Resource CD into your CD-ROM drive, click Start and choose Run. In the field that appears, enter F:\XXX\Setup.exe (if “F” is the letter of.
CS378 - Mobile Computing Intents. Allow us to use applications and components that are part of Android System – start activities – start services – deliver.
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.
Cosc 5/4730 Android Communications Intents, callbacks, and setters.
Introduction to Socket Programming in Android Jules White Bradley Dept. of Electrical and Computer Engineering Virginia Tech
CE Operating Systems Lecture 13 Linux/Unix interprocess communication.
LAN Switching and Wireless Basic Switch Concepts and Configuration.
Applications with Multiple Activities. Most applications will have more than one activity. The main activity is started when the application is started.
GPRS functionality overview in Horner OCS. GPRS functionality – Peer to Peer communication over GPRS – CSCAPE connectivity over GPRS – Data exchange using.
WIRELESS COMMUNICATION Husnain Sherazi Lecture 1.
Don’t Log in!. Recap on the previous units I’ve tried to make it as concise as possible but there is a bit of writing, to ensure that you have some notes.
Lecture 2: Android Concepts
Agenda Socket Programming The OSI reference Model The OSI protocol stack Sockets Ports Java classes for sockets Input stream and.
Nguyen Thi Thanh Nha HMCL by Roelof Kemp, Nicholas Palmer, Thilo Kielmann, and Henri Bal MOBICASE 2010, LNICST 2012 Cuckoo: A Computation Offloading Framework.
Horizon Photo-mote. ability to access photographs and images stored online, with the aid of a wireless remote remote enables the user to identify and.
1 Philips EvoKit Lumen Selection App User Manual * Philips Lighting April 20, 2016 *Can be used for Philips EvoBase as well.
Intents and Broadcast Receivers Dr. David Janzen Except as otherwise noted, the content of this presentation is licensed under the Creative Commons Attribution.
LINCWorks Mesh Networking User Guide. This user guide will give a brief overview of mesh networking followed by step by step instructions for configuring.
LAN Switching Virtual LANs. Virtual LAN Concepts A LAN includes all devices in the same broadcast domain. A broadcast domain includes the set of all LAN-connected.
Services. What is a Service? A Service is not a separate process. A Service is not a thread. A Service itself is actually very simple, providing two main.
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.
Presenter: Tyler Newsome
CS434/534: Topics in Networked (Networking) Systems Mobile Networking System: Making Connections: Bluetooth; WiFi Direct; Cellular Yang (Richard) Yang.
Intents and Broadcast Receivers
Instructor Materials Chapter 6 Building a Home Network
Bluetooth.
Wireless Technologies
Broadcast receivers.
Lecture 7: Service Topics: Services, Playing Media.
Instructor: Mazhar Hussain
Wireless Communication between Android Application and Sensors
Short-Range Radio Frequency Networking
Short-Range Radio Frequency Networking
Android Developer Fundamentals V2 Lesson 5
Lecture 7: Service Topics: Services, Broadcast Receiver, Playing Media.
Mobile Programming Dr. Mohsin Ali Memon.
Presentation transcript:

Wireless Networking with Android Uichin Lee KAIST KSE

Review Wireless link characteristics 802.11 WLAN (a, b, g, n) channels, associations, scanning multiple access: CSMA/CA (RTS-CTS-DATA-ACK) PAN: Bluetooth master vs. slave peer discovery (inquiry) + connection setup (paging) piconet (up to 7 slaves)

SNR RSS: received signal strength SNR: signal to noise ratio . SNR RSS: received signal strength Measure of the power present in a received radio signal (at the receiver antenna) Represented in decibels above a reference level of 1 mW (dBm) WiFi: 100mW (20dBm): EIRP for IEEE 802.11b/g Wireless LAN 20Mhz-wide channels in the 2.4GHz ISM band (5mW per MHz). Typical range (−60 to −80 dBm) of wireless received signal power -60dBm => 0.0000001 mW SNR: signal to noise ratio SNR = Eb/No where Eb the energy per bit, and No noise power spectral density SNR = (Signal Power/Bit Rate) / (Noise Power/Filter Bandwidth) CNR = Signal Power / Noise Power BER is a function of SNR; e.g., BER(BPSK) = ½erfc(sqrt(SNR))

Internet Switch Switches Filtering: whether a frame should be forwarded to some interface or should be dropped Forwarding: determining the interfaces to which a frame should be directed; and then moves the frame to those interfaces Switch filtering and forwarding are done with a switch table ADDR X: Interface Y: address X comes from interface Y Elimination of collisions: No wastage of bandwidth thanks to buffers Switch buffers frames and never transmit more than one frame on a segment at any one time Switch provides a significant performance improvement over LANs with broadcast links

Managing network connectivity Android broadcasts Intents that describe the changes in network connectivity 3G, WiFi, etc. There are APIs for controlling network settings and connections Android networking is handled by ConnectivityManager (a network connectivity service) Monitor the state of network connections Configure failover settings Control network radios

Managing network connectivity Accessing connectivity manager App needs read/write access permission on network states String service = Context.CONNECTIVITY_SERVICE; ConnectivityManager connectivity = (ConnectivityManager) getSystemService(service); <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>

Accessing network status // Get the active network information. NetworkInfo activeNetwork = connectivity.getActiveNetworkInfo(); int networkType = activeNetwork.getType(); switch (networkType) { case (ConnectivityManager.TYPE_MOBILE) : break; case (ConnectivityManager.TYPE_WIFI) : break; default: break; } // Get the mobile network information. int network = ConnectivityManager.TYPE_MOBILE; NetworkInfo mobileNetwork = connectivity.getNetworkInfo(network); NetworkInfo.State state = mobileNetwork.getState(); NetworkInfo.DetailedState detailedState = mobileNetwork.getDetailedState();

Preferred networks Preferred network configuration: getNetworkPreference() setNetworkPreference() If the preferred connection is unavailable, or connectivity on this network is lost, Android will automatically attempt to connect to the secondary network. Control availability of the network types using the setRadio() method. int networkPreference = connectivity.getNetworkPreference(); connectivity.setNetworkPreference(NetworkPreference.PREFER_WIFI); connectivity.setRadio(NetworkType.WIFI, false); connectivity.setRadio(NetworkType.MOBILE, true);

Based on “Programming Android 2” WiFi Based on “Programming Android 2”

Managing your WiFi WifiManager: represents the Android WiFi connectivity service Configure WiFi network connections Manage current WiFi connection Scan for access points Monitor changes in WiFi connectivities

Monitoring WiFi connectivity Accessing the WiFi Manager Monitoring and changing Wifi state State: enabling, enabled, disabling, disabled, and unknown String service = Context.WIFI_SERVICE; WifiManager wifi = (WifiManager) getSystemService(service); <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/> if (!wifi.isWifiEnabled()) if (wifi.getWifiState() != WifiManager.WIFI_STATE_ENABLING) wifi.setWifiEnabled(true);

Monitoring WiFi connectivity WifiManager broadcasts Intents whenever connectivity status changes WIFI_STATE_CHANGED_ACTION Wi-Fi h/w status has changed: enabling, enabled, disabling, disabled, and unknown EXTRA_WIFI_STATE, EXTRA_PREVIOUS_STATE SUPPLICANT_CONNECTION_CHANGED_ACTION: Whenever connection state with the active supplicant (access point) changes Fired when a new conn is established, or existing conn is lost (EXTRA_NEW_STATE = true/false) NEWTWORK_STATE_CHANGED_ACTION: Fired whenever wifi connectivity state changes EXTRA_NETWORK_INFO: NetworkInfo obj for current network status EXTRA_BSSID: BSSID of the access point that you’re connected to RSSI_CHANGED_ACTION: Monitor the signal strength of the connected WiFi network EXTRA_NEW_RSSI: current signal strength

Monitoring active connection details Once you connected to an access point, use getConnectionInfo of WifiManager to find info of that connection Returns “WifiInfo” object WifiInfo info = wifi.getConnectionInfo(); if (info.getBSSID() != null) { int strength = WifiManager.calculateSignalLevel(info.getRssi(), 5); int speed = info.getLinkSpeed(); String units = WifiInfo.LINK_SPEED_UNITS; String ssid = info.getSSID(); String cSummary = String.format("Connected to %s at %s%s. Strength %s/5", ssid, speed, units, strength); }

Scanning hotspots Use WifiManager to scan access points using startScan() Android will broadcast scan results with an Intent of “SCAN_RESULTS_AVAILABLE_ACTION” // Register a broadcast receiver that listens for scan results. registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { List<ScanResult> results = wifi.getScanResults(); ScanResult bestSignal = null; for (ScanResult result : results) { if (bestSignal == null || WifiManager.compareSignalLevel(bestSignal.level,result.level)<0) bestSignal = result; } String toastText = String.format("%s networks found. %s is the strongest.", results.size(), bestSignal.SSID); Toast.makeText(getApplicationContext(), toastText, Toast.LENGTH_LONG); }, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)); // Initiate a scan. wifi.startScan();

Creating a WiFi configuration To connect to a WiFi network, a WiFi configuration must be created and registered Normally a user does this, but app can do this Network configuration is stored as WifiConfiguration object SSID (service set ID, e.g., IPv4_KAIST) BSSID (MAC addr of an AP) networkId (unique ID that the supplicant uses to identify this network configuration entry) priority (priority of this access point) status (current status: ENABLED, DISABLED, CURRENT)

Creating a WiFi configuration WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE); WifiConfiguration wc = new WifiConfiguration(); wc.SSID = "\"SSIDName\""; wc.preSharedKey  = "\"password\""; // it should be in double quote “password” wc.hiddenSSID = true; wc.status = WifiConfiguration.Status.ENABLED;   // setting up WPA-PSK     wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN); int res = wifi.addNetwork(wc); // the ID of the newly created network description Log.d("WifiPreference", "add Network returned " + res ); boolean b = wifi.enableNetwork(res, true);         Log.d("WifiPreference", "enableNetwork returned " + b ); http://stackoverflow.com/questions/2140133/how-and-what-to-set-to-android-wificonfiguration-presharedkey-to-connect-to-the-w http://developer.android.com/reference/android/net/wifi/WifiConfiguration.html#preSharedKey

Managing WiFi configurations Use WiFi Manager to manage the configured network settings and control which networks to connect to // Get a list of available configurations List<WifiConfiguration> configurations = wifi.getConfiguredNetworks(); // Get the network ID for the first one. if (configurations.size() > 0) { int netID = configurations.get(0).networkId; // Enable that network. boolean disableAllOthers = true; wifi.enableNetwork(netID, disableAllOtherstrue); }

Power Management Android supports its own Power Management (on top of the standard Linux Power Management) To make sure that CPU shouldn't consume power if no applications or services require power Android requires that applications and services request CPU resources with "wake locks" through the Android application framework and native Linux libraries. If there are no active wake locks, Android will shut down the CPU.

Power Management http://www.kandroid.org/android_pdk/power_management.html

WakeLock Flag value CPU Screen Keyboard PARTIAL_WAKE_LOCK On Off SCREEN_DIM_WAKE_LOCK Dim SCREEN_BRIGHT_WAKE_LOCK BRIGHT FULL_WAKE_LOCK Bright // Acquire handle to the PowerManager service PowerManager pm = (PowerManager)mContext.getSystemService( Context.POWER_SERVICE); // Create a wake lock and specify the power management flags for screen, timeout, etc. PowerManager.WakeLock wl = pm.newWakeLock( PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, TAG); // Acquire wake lock wl.acquire(); // ... // Release wake lock wl.release(); PowerManager.ON_AFTER_RELEASE: When this wake lock is released, poke the user activity timer so the screen stays on for a little longer.

Wifi background data transfer Wifilock + Wakelock (partial) // http://developer.android.com/reference/android/net/wifi/WifiManager.WifiLock.html WifiManager.WifiLock wifiLock = null; PowerManager.WakeLock wakeLock = null; // acquire if (wifiLock == null) { WifiManager wifiManager = (WifiManager) context.getSystemService(context.WIFI_SERVICE); wifiLock = wifiManager.createWifiLock("wifilock"); wifiLock.setReferenceCounted(true); wifiLock.acquire(); PowerManager powerManager = (PowerManager) context.getSystemService(context.POWER_SERVICE); wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "wakelock"); wakeLock.acquire(); } // release if (wifiLock != null) { wifiLock.release(); wifiLock = null; wakeLock.release(); wakeLock = null;

Background data transfer Setting > Accounts & sync settings > background data setting If this setting is off, an application cannot transfer data only when it is active and in the foreground Services cannot transfer data (by definition) Use connectivity manager to check this: boolean backgroundEnabled = connectivity.getBackgroundDataSetting(); App can listen to changes in the background data transfer preference: registerReceiver( new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) // do something.. }, new IntentFilter(ConnectivityManager. ACTION_BACKGROUND_DATA_SERVICE_CHANGED) );

Bluetooth Based on “Programming Android 2” Android Developer Guide: http://developer.android.com/guide/topics/wireless/bluetooth.html

Main classes BluetoothAdapter: BluetoothDevice: BluetoothSocket: local Bluetooth device BluetoothDevice: representing each remote device with which we want to communicate with BluetoothSocket: call “createRfcommSocketToServiceRecord()” on a remote Bluetooth Device object to create a Bluetooth socket BluetoothServerSocket: creating a Bluetooth server socket by calling “listenUsingRfcommWithServiceRecord()” method

Overview Master (initiator) Slave Peer discovery: get a list of neighboring peers Setting BT as “discoverable” => respond to peer inquiry Connect to a slave: socket.connect(“one of slaves”); (act as a client) Accepting incoming connections: Socket.accept() (act as a server)

Bluetooth permissions To use Bluetooth features, at least one of two Bluetooth permissions must be declared: BLUETOOTH Requesting/accepting a connection, and data transfer BLUETOOTH_ADMIN More powerful than BLUETOOTH; includes device discovery, manipulating Bluetooth settings (on/off), etc. <manifest ... >   <uses-permission android:name="android.permission.BLUETOOTH" />   ... </manifest>

Setting up Bluetooth Bluetooth setup: Get the BluetoothAdapter 2. Enable Bluetooth BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) {     // Device does not support Bluetooth } if (!mBluetoothAdapter.isEnabled()) {     Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);     startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_ENABLE_BT) if (resultCode == RESULT_OK ) // if user pressed “YES” if (resultCode == RESULT_CANCELED) { // if user pressed “NO” }

Setting up Bluetooth App can also listen for “ACTION_STATE_CHANGED” broadcast intent Android will broadcast whenever the Bluetooth state has changed Broadcast contains the extra fields: EXTRA_STATE: current state EXTRA_PREVIOUS_STATE: previous state State values: STATE_TURNING__ON STATE_ON STATE_TURNING_OFF STATE_OFF Enabling “discoverability” will automatically enable Bluetooth

Discoverability (slave) Enabling “discoverability” New intent with “ACTION_REQUEST_DISCOVERABLE” This will show a user permission dialog: Activity will receive the response through “onActivityResult()” Activity.RESULT_CANCELLED (if a user canceled) The device will be “discoverable” for the specified duration (default: 2 minutes) App can be notified of mode changes by registering a BroadcastReceiver for the “ACTION_SCAN_MODE_CHANGED” Intent EXTRA_SCAN_MODE EXTRA_SCAN_MODE_PREVIOUS Values: SCAN_MODE_CONNECTABLE_DISCOVERABLE (inquiry scan + page scan on), SCAN_MODE_CONNECTABLE (page scan on), SCAN_MODE_NONE (none) App does not need to enable device “discoverablity” if you will be initiating a connection to a remote node Only necessary when other parties discover an app that hosts a server socket for accepting incoming connections Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); startActivityForResult(discoverableIntent, DISCOVERY_REQUEST);

Discovering devices (master) Call “startDiscovery()” – async method (about 12 second inquiry) BluetoothAdapter bt = BluetoothAdapter.getDefaultAdapter(); bt.startDiscovery(); App registers a BroadcastReceiver for the ACTION_FOUND Intent to receive information about each device discovered It carries the extra fields: EXTRA_DEVICE (BluetoothDevice) and EXTRA_CLASS (BluetoothClass) Call “cancelDiscovery()” to cancel discovery (check first with isDiscovering()) // Create a BroadcastReceiver for ACTION_FOUND private final BroadcastReceiver mReceiver = new BroadcastReceiver() {     public void onReceive(Context context, Intent intent) {         String action = intent.getAction();         // When discovery finds a device         if (BluetoothDevice.ACTION_FOUND.equals(action)) {             // 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

Device pairing (master/slave) Device pairing (or bonding) When a connection is made with a remote device for the first time, a pairing request is automatically presented to the user When paired, basic information about a device is kept locally such as device name, class, MAC addr, some secret keys (for secure comm) Android Bluetooth APIs require devices to be paired before an RFCOMM connection can be established

Socket communications (slave) Server must hold an open BluetoothServerSocket Procedure: Get BluetoothServerSocket by calling listenUsingRfcommWithServiceRecord(String, UUID) String is a name of your service written into Service Discovery Protocol (SDP) DB UUID is an entry in SDP DB (unique service identifier) Listening for connection requests by calling accept() Blocking call; return a connection if accepted Matching if a remote device sent a req with a UUID matching the one registered with this listening server socket

Socket communications (slave) private class AcceptThread extends Thread {     private final BluetoothServerSocket mmServerSocket;     public AcceptThread() {         BluetoothServerSocket tmp = null;         try {             // MY_UUID is the app's UUID string, also used by the client code             tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);         } catch (IOException e) { }         mmServerSocket = tmp;     }     public void run() {         BluetoothSocket socket = null;         // Keep listening until exception occurs or a socket is returned         while (true) {             try {                 socket = mmServerSocket.accept();             } catch (IOException e) { break; }             // If a connection was accepted             if (socket != null) {                 // Do work to manage the connection (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 (IOException e) { }     } }

Socket communications (master) Must have “BluetoothDevice” of a remote device (discovered via startDiscovery()) Procedure: Using BluetoothDevice, get a BluetoothSocket by calling “createRfcommSocketToServiceRecord(UUID)” Initialize a BluetoothSocket with a given UUID UUID is a hard-coded string unique to the “server” Initiate a connection by calling “connect()” System will perform an SDP lookup on the remote device to match the UUID If the lookup is successful and the remote device accepts the connection, it will share the RFCOMM channel for comm

Socket communications (master) private class ConnectThread extends Thread {     private final BluetoothSocket mmSocket;     private final BluetoothDevice mmDevice;     public ConnectThread(BluetoothDevice device) {         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 (IOException e) { }         mmSocket = tmp;     }     public void run() {         try {             // Connect the device through the socket. This will block             // until it succeeds or throws an exception             mmSocket.connect();         } catch (IOException connectException) {             // Unable to connect; close the socket and get out             try {                 mmSocket.close();             } catch (IOException closeException) { }             return;         }         // Do work to manage the connection (in a separate thread)         manageConnectedSocket(mmSocket);     }     public void cancel() {         try {             mmSocket.close();         } catch (IOException e) { }     }

Managing a connection Each device now has a connected BluetoothSocket Sending/receiving data: First get InputStream/OutputStream from socket Read/write data to the streams with blocking calls, read/write(byte[])

Managing a connection 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 (IOException e) { }         mmInStream = tmpIn;         mmOutStream = tmpOut; }     public void run() {         byte[] buffer = new byte[1024];  // buffer store for the stream         int bytes; // bytes returned from read()       while (true) {             try {                 // Read from the InputStream                 bytes = mmInStream.read(buffer);                 // Send the obtained bytes to the UI Activity                 mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)                         .sendToTarget();             } catch (IOException e) { break; }         }     } Source: http://developer.android.com/resources/samples/BluetoothChat/ http://developer.android.com/reference/android/os/Handler.html A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue. There are two main uses for a Handler: (1) to schedule messages and runnables to be executed as some point in the future; and (2) to enqueue an action to be performed on a different thread than your own. Scheduling messages is accomplished with the post(Runnable), postAtTime(Runnable, long), postDelayed(Runnable, long), sendEmptyMessage(int),sendMessage(Message), sendMessageAtTime(Message, long), and sendMessageDelayed(Message, long) methods. The post versions allow you to enqueue Runnable objects to be called by the message queue when they are received; the sendMessage versions allow you to enqueue a Message object containing a bundle of data that will be processed by the Handler's handleMessage(Message) method (requiring that you implement a subclass of Handler). When posting or sending to a Handler, you can either allow the item to be processed as soon as the message queue is ready to do so, or specify a delay before it gets processed or absolute time for it to be processed. The latter two allow you to implement timeouts, ticks, and other timing-based behavior. When a process is created for your application, its main thread is dedicated to running a message queue that takes care of managing the top-level application objects (activities, broadcast receivers, etc) and any windows they create. You can create your own threads, and communicate back with the main application thread through a Handler. This is done by calling the same post or sendMessage methods as before, but from your new thread. The given Runnable or Message will then be scheduled in the Handler's message queue and processed when appropriate. Handler code: private final Handler mHandler = new Handler() {         @Override         public void handleMessage(Message msg) {             switch (msg.what) {             case MESSAGE_STATE_CHANGE:                 if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);                 switch (msg.arg1) {                 case BluetoothChatService.STATE_CONNECTED:                     setStatus(getString(R.string.title_connected_to, mConnectedDeviceName));                     mConversationArrayAdapter.clear();                     break;                 case BluetoothChatService.STATE_CONNECTING:                     setStatus(R.string.title_connecting);                     break;                 case BluetoothChatService.STATE_LISTEN:                 case BluetoothChatService.STATE_NONE:                     setStatus(R.string.title_not_connected);                     break;                 }                 break;             case MESSAGE_WRITE:                 byte[] writeBuf = (byte[]) msg.obj;                 // construct a string from the buffer                 String writeMessage = new String(writeBuf);                 mConversationArrayAdapter.add("Me:  " + writeMessage);                 break;             case MESSAGE_READ:                 byte[] readBuf = (byte[]) msg.obj;                 // construct a string from the valid bytes in the buffer                 String readMessage = new String(readBuf, 0, msg.arg1);                 mConversationArrayAdapter.add(mConnectedDeviceName+":  " + readMessage);                 break;             case MESSAGE_DEVICE_NAME:                 // save the connected device's name                 mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);                 Toast.makeText(getApplicationContext(), "Connected to "                                + mConnectedDeviceName, Toast.LENGTH_SHORT).show();                 break;             case MESSAGE_TOAST:                 Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),                                Toast.LENGTH_SHORT).show();                 break;             }         }     };

NFC Reading NDEF data from an NFC tag Beaming NDEF messages from one device to another with Android Beam http://developer.android.com/guide/topics/nfc/nfc.html http://developer.android.com/resources/samples/AndroidBeamDemo/src/com/example/android/beam/Beam.html

NFC: Near Field Communications

NFC Forum Technology Architecture NFC device NFC tag NFC card emulation mode: Smart key say for mobile local payment P2P mode (Android Beam): either directly or by establishing wireless links http://www.nfc-forum.org/events/oulu_spotlight/Technical_Architecture.pdf Reader/writer mode: low cost solution to distribute info/services http://www.nfc-forum.org/events/oulu_spotlight/Technical_Architecture.pdf

NFC Capabilities on Android Currently available Android NFC phones: Google Nexus S, Samsung Galaxy S 2 Use Android 2.3.3 (API Level 10) as the NFC APIs drastically changed from 2.3.2. NFC in Android: Tag reader/writer P2P communication (Android-specific) Tag emulation (of certain NFC NDEF tags) – not fully functional* * http://stackoverflow.com/questions/6138077/can-an-android-nfc-phone-act-as-an-nfc-tag

Tag Dispatch System Android-powered devices are usually looking for NFC tags when the screen is unlocked, unless NFC is disabled in the device's Settings menu. Tag dispatch system analyzes scanned NFC tags, parses them, and tries to locate applications that are interested in the scanned data

Reading Tag Example <manifest ... > <uses-permission android:name="android.permission.NFC" /> <uses-sdk android:minSdkVersion="10"/> <uses-feature android:name="android.hardware.nfc" android:required="true" /> </manifest> <intent-filter>   <action android:name="android.nfc.action.NDEF_DISCOVERED"/>   <category android:name="android.intent.category.DEFAULT"/> // The following example filters for a URI in the form of http://developer.android.com/index.html.    <data android:scheme="http"               android:host="developer.android.com"               android:pathPrefix="/index.html" /> // for P2P beaming.. <data android:mimeType="application/com.example.android.beam" /> </intent-filter>

Reading Tag Example public void onResume() { super.onResume(); ...     if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {         Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);         if (rawMsgs != null) {             msgs = new NdefMessage[rawMsgs.length];             for (int i = 0; i < rawMsgs.length; i++) {                 msgs[i] = (NdefMessage) rawMsgs[i];             }         }     }     //process the msgs array }

Android Beaming (P2P) Simple P2P data exchange between two Android-powered devices Sender app must be in the foreground Receiver must not be locked Sender’s close contact will invoke "Touch to Beam" UI Sender can then choose whether or not to beam the message to receiver Note that if your activity enables Android Beam and is in the foreground, the standard intent dispatch system will be disabled. However, if your activity also enables foreground dispatching, then it can still scan tags that match the intent filters set in the foreground dispatching. http://stackoverflow.com/questions/3919089/do-callbacks-occur-on-the-main-ui-thread (difference) http://stackoverflow.com/questions/7509340/differences-b-w-intent-dispatch-system-and-foreground-dispatch-system The intent dispatch system is to launch a program from scratch. For instance, you turn your phone on and hover it over a tag. The phone launches an intent, identifying it as a Mifare card. Your app has an intent dispatch for Mifare cards, so it is one of the apps that can be selected. If your intent dispatch is specific enough(compared to other apps), it will be the only app to select, and will run at that point. Foreground dispatch is used by your app while it is running. This way, your app won't be turned off if another app has a similar intent dispatch setup. Now with your app running, it can discover a tag and handle the intent over other apps on the phone, and the phone will not prompt you to select from a bunch of apps that have a similar intent dispatch. I hope that was not to confusing!

Android Beaming (P2P) // Register callback to set NDEF message (OnCreate) mNfcAdapter.setNdefPushMessageCallback(this, this); // Register callback to listen for message-sent success mNfcAdapter.setOnNdefPushCompleteCallback(this, this); NfcAdapter.CreateNdefMessageCallback.createNdefMessage(NfcEvent event) NfcAdapter.OnNdefPushCompleteCallbackon.NdefPushComplete(NfcEvent event) CreateNdefMessageCallBack causes a Callback to be invoked when another NFC device capable of NDEF push (Android Beam) is within range. Instantly create an NdefMessage at the moment that another device is within range for NFC and push it over (pushing is done automatically). Using this callback allows you to create a message with data that might vary based on the content currently visible to the user. OnNdefPushCompleteCallbackon causes a Callback as soon as sending of the NDEF Message is completed. You should implement this method in order to let the user know, when the transfer is complete and thus the user can put his NFC device away. http://developer.android.com/resources/samples/AndroidBeamDemo/src/com/example/android/beam/Beam.html

Android Beaming (P2P) // Receiving a beam from the sender     @Override     public void onNewIntent(Intent intent) {         // onResume gets called after this to handle the intent         setIntent(intent);     }     @Override     public void onResume() {         super.onResume();         // Check to see that the Activity started due to an Android Beam         if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {             processIntent(getIntent());         }     } // Parses the NDEF Message from the intent and prints to the TextView     void processIntent(Intent intent) {         Parcelable[] rawMsgs = intent.getParcelableArrayExtra(                 NfcAdapter.EXTRA_NDEF_MESSAGES);         // only one message sent during the beam         NdefMessage msg = (NdefMessage) rawMsgs[0];         // record 0 contains the MIME type, record 1 is the AAR, if present         mInfoText.setText(new String(msg.getRecords()[0].getPayload()));     } Note: If your activity enables Android Beam and is in the foreground, the standard intent dispatch system is disabled. However, if your activity also enables foreground dispatching, then it can still scan tags that match the intent filters set in the foreground dispatching. http://developer.android.com/resources/samples/AndroidBeamDemo/src/com/example/android/beam/Beam.html

Summary Managing network connectivity WiFi management Bluetooth communications through RFCOMM NFC: tag reading and beaming