Wireless Networking with Android Uichin Lee KAIST KSE
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);
Accessing network status // Get the active network information. NetworkInfo activeNetwork = connectivity.getActiveNetworkInfo(); int networkType = networkInfo.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. connectivity.setRadio(NetworkType.WIFI, false); connectivity.setRadio(NetworkType.MOBILE, true); int networkPreference = connectivity.getNetworkPreference(); connectivity.setNetworkPreference(NetworkPreference.PREFER_WIFI);
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); 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 Wifi 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() public void onReceive(Context context, Intent intent) { List 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 );
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 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
WakeLock Flag valueCPUScreenKeyboard PARTIAL_WAKE_LOCKOnOff SCREEN_DIM_WAKE_LOCKOnDimOff SCREEN_BRIGHT_WAKE_LOCKOnBRIGHTOff FULL_WAKE_LOCKOnBright // 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();
Wifi background data transfer Background data transfer: – Wifilock + Wakelock (partial) // 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() 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:
Main classes BluetoothAdapter: – 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
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....
Setting up Bluetooth Bluetooth setup: 1.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); 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
Finding devices 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);
Finding devices Discovering devices – 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
Finding devices 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
Connecting devices (server) Server must hold an open BluetoothServerSocket Procedure: 1.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) 2.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
Connecting devices (server) 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) { } } }
Connecting devices (client) Must have “BluetoothDevice” of a remote device (discovered via startDiscovery()) Procedure: 1.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” 2.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
Connecting devices (client) 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; } } }
Summary Managing network connectivity WiFi management Bluetooth communications through RFCOMM HW: run “Bluetooth Chat” –