Presentation is loading. Please wait.

Presentation is loading. Please wait.

Bluetooth. Bluetooth is an open, wireless protocol for exchanging data between devices over a short distance. –managed by the Bluetooth Special Interest.

Similar presentations


Presentation on theme: "Bluetooth. Bluetooth is an open, wireless protocol for exchanging data between devices over a short distance. –managed by the Bluetooth Special Interest."— Presentation transcript:

1 Bluetooth

2 Bluetooth is an open, wireless protocol for exchanging data between devices over a short distance. –managed by the Bluetooth Special Interest Group –originally standardized as IEEE Standard 802.15.1, but the standard is no longer maintained Common Example: Connecting a phone to a hands-free headset; e.g., for use when driving an automobile. Using the Android Bluetooth APIs, an application can –scan for other Bluetooth devices –query the local Bluetooth adapter for paired Bluetooth devices –connect to other devices –transfer data to and from other devices Slide 2©SoftMoore Consulting

3 Primary Classes of the Bluetooth API (package android.bluetooth ) BluetoothAdapter –the local Bluetooth radio –entry-point for all Bluetooth interaction BluetoothDevice –a remote Bluetooth device BluetoothSocket –connection point for exchange data with another Bluetooth device via InputStream and OutputStream BluetoothServerSocket –an open server socket that listens for incoming requests BluetoothClass –general characteristics and capabilities of the Bluetooth device Slide 3©SoftMoore Consulting

4 Bluetooth Permissions Permission BLUETOOTH –to perform any Bluetooth communication, such as requesting a connection, accepting a connection, and transferring data Permission BLUETOOTH_ADMIN –to initiate device discovery or manipulate Bluetooth settings Example <uses-permission android:name ="android.permission.BLUETOOTH" /> <uses-permission android:name ="android.permission.BLUETOOTH_ADMIN" />... Slide 4©SoftMoore Consulting

5 Four Major Tasks for Communicating Using Bluetooth 1. Setting up Bluetooth 2. Finding devices that are either paired (a.k.a., bonded) or available in the local area 3. Connecting devices 4. Transferring data between devices Slide 5©SoftMoore Consulting

6 Setting Up Bluetooth: Get a BluetoothAdapter Import the Bluetooth package import android.bluetooth.*; Get the BluetoothAdapter –call static method getDefaultAdapter() –returns a BluetoothAdapter that represents the device’s own Bluetooth adapter (the Bluetooth radio) –returns null if the device does not have a Bluetooth adapter Slide 6©SoftMoore Consulting Note: The question of whether or not a device has a Bluetooth adapter is separate for the question of whether or not the Bluetooth adapter is turned on (enabled).

7 Example: Get a BluetoothAdapter // defined as an instance variable private BluetoothAdapter bluetoothAdapter; // in the activity's onCreate() method bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter == null) { // device does not have a bluetooth adapter... } Slide 7©SoftMoore Consulting For Android API levels 17 and higher, the following code can also be used to obtain a Bluetooth adapter: BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE); bluetoothAdapter = bluetoothManager.getAdapter();

8 Setting Up Bluetooth: Enable Bluetooth Enable Bluetooth –call isEnabled() to check if Bluetooth is currently enable –returns false if Bluetooth is disabled To request that Bluetooth be enabled –create an Intent with action BluetoothAdapter.ACTION_REQUEST_ENABLE –call startActivityForResult(). Slide 8©SoftMoore Consulting

9 Example: Enable Bluetooth // define constant for request code (must be greater than 0) private static final int REQUEST_ENABLE_BT = 3; // in the onCreate() method or a separate method if (!bluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } Slide 9©SoftMoore Consulting

10 Example: Enable Bluetooth (continued) A dialog will appear requesting user permission to enable Bluetooth If user responds “Allow”, the system will start to enable Bluetooth. –If Bluetooth is successfully enabled, the activity receives the RESULT_OK result code in the onActivityResult() callback. –If the user responds “No” or if Bluetooth was not enabled due to an error, then the result code is RESULT_CANCELED. Slide 10©SoftMoore Consulting

11 Example: Enable Bluetooth (continued) @Override protected void onActivityResult( int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_ENABLE_BT && resultCode == RESULT_OK) { // Bluetooth has been enabled.... } else { // Bluetooth was not enabled.... } Slide 11©SoftMoore Consulting

12 Finding Devices Two ways to find Remote Bluetooth devices: Through device discovery (a.k.a., inquiring or scanning) By querying the adapter to get the set of previously paired (a.k.a., bonded) devices. Slide 12©SoftMoore Consulting

13 Bonded Devices Bonded Bluetooth devices are devices that have paired with the current device sometime in the past. When a remote device is paired (bonded), basic information about that device is saved and can be read using the Bluetooth APIs. Saved device information can include –device name –class (computer, phone, etc.) –MAC address To get the bonded Bluetooth devices, call the BluetoothAdapter method getBondedDevices(). Slide 13©SoftMoore Consulting

14 Example: Obtaining the Set of Bonded Devices Set pairedDevices = bluetoothAdapter.getBondedDevices(); for (BluetoothDevice device : pairedDevices) {... } Slide 14©SoftMoore Consulting

15 Difference Between Being Paired and Being Connected. To be paired means that two devices are aware of each other’s existence, have a shared link-key that can be used for authentication, and are capable of establishing an encrypted connection with each other. To be connected means that the devices currently share an RFCOMM (the Bluetooth transport protocol) channel and are able to transmit data with each other. –Android requires devices to be paired before an RFCOMM connection can be established. –Pairing is automatically performed when you initiate an encrypted connection with the Bluetooth APIs. Slide 15©SoftMoore Consulting

16 Discovering Devices Device discovery is a scanning procedure that searches the local area for Bluetooth enabled devices and then requests some information about each one. A Bluetooth device within the local area will respond to a discovery request only if it is currently enabled to be discoverable. Slide 16©SoftMoore Consulting Note: Android-powered devices are not discoverable by default. A user can make the device discoverable for a limited time through the system settings, or an application can request that the user enable discoverability.

17 Discovering Devices (continued) If a device is discoverable, it will respond to the discovery request by sharing some information, such as the device name, class, and its unique MAC address. Using this information, the device performing discovery can then choose to initiate a connection to the discovered device. Slide 17©SoftMoore Consulting

18 Process for Discovering Devices Register a BroadcastReceiver for the ACTION_FOUND Intent in order to receive information about each device discovered. –system will broadcast the ACTION_FOUND Intent for each device –the Intent carries the extra fields EXTRA_DEVICE (a BluetoothDevice ) EXTRA_CLASS (a BluetoothClass ) Call startDiscovery() to initiate device discovery. –process is asynchronous –method returns immediately with a boolean indicating whether discovery has successfully started –process usually involves an inquiry scan of about 120 seconds, followed by a page scan of each found device to retrieve its Bluetooth name Slide 18©SoftMoore Consulting

19 Example: Create a Broadcast Receiver // defined as an instance variable for the activity private HashMap discoveredDevices = new HashMap (); // defined as an inner class within the activitiy private class BluetoothBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(BluetoothDevice.ACTION_FOUND)) { BluetoothDevice device = intent. getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); discoveredDevices.put(device.getName(), device); } Slide 19©SoftMoore Consulting

20 Example: Register the Broadcast Receiver // defined as an instance variable for the activity private BluetoothBroadcastReceiver receiver; // in the activity's onCreate() method receiver = new BluetoothBroadcastReceiver(); IntentFilter actionFoundFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND); registerReceiver(receiver, actionFoundFilter); if (bluetoothAdapter.startDiscovery()) {... // show Toast "Bluetooth discovery started" } Slide 20©SoftMoore Consulting Note: You also can register the broadcast receiver to receive other events; e.g., BluetoothAdapter.ACTION_STATE_CHANGED.

21 Enabling Discovery To make an android device discoverable, call method startActivityForResult(Intent, int) with the action intent ACTION_REQUEST_DISCOVERABLE. By default, the device will become discoverable for 120 seconds. –define a different duration by adding the intent extra EXTRA_DISCOVERABLE_DURATION –maximum duration an app can set is 3600 seconds –value of 0 means the device is always discoverable A dialog will be displayed, requesting user permission to make the device discoverable. Slide 21©SoftMoore Consulting

22 Enabling Discovery (continued) Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableIntent.putExtra (BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 200); startActivity(discoverableIntent); Slide 22©SoftMoore Consulting

23 Connecting Bluetooth Devices Similar to TCP connections, Bluetooth devices connect with each other using a client-server model based on sockets and streams. Client initiates connection with server –sends request to server for data –displays data and responds to user input Server listens for connection requests from clients –receives request from client –formulates response and sends response to client Slide 23©SoftMoore Consulting Difference between client and server is relative. It’s just peers talking to each other.

24 UUIDs Android Bluetooth applications use a Universally Unique Identifier (UUID) to identify the application. A UUID is a standardized 128-bit format for a string ID used to uniquely identify information. –see class java.util.UUID –easy to generate using this class or one of the many random UUID generators on the web Example System.out.println(UUID.randomUUID()); Output: 3964633a-f2e8-475a-9642-7805d6c36fa7 Slide 24©SoftMoore Consulting

25 Connecting Bluetooth Devices: Programming the Server The server creates a BluetoothServerSocket. BluetoothServerSocket btServerSocket = bluetoothAdapter.listenUsingRfcommWithServiceRecord (APP_NAME, APP_UUID); The server then calls the accept() method to listen for connection requests from clients. BluetoothSocket btSocket = btServerSocket.accept(); This is a blocking call in that it will return when either a connection has been accepted or an exception has occurred. –must be called in a non-UI thread Slide 25©SoftMoore Consulting

26 Connecting Bluetooth Devices: Programming the Server (continued) A connection is accepted only when a remote device has sent a connection request with a UUID matching the one registered with this listening server socket. When a connection has been accepted, call close() –releases the server socket and all its resources –does not close the BluetoothSocket returned by accept() Unlike TCP/IP, RFCOMM only allows one connected client per channel at a time, so in most cases it makes sense to call close() on the BluetoothServerSocket immediately after accepting a connected socket. Slide 26©SoftMoore Consulting

27 Class BluetoothSocket Similar to TCP sockets in Java, BluetoothSocket provides input and output streams for communicating with a remote device. OutputStream outStream = btSocket.getOutputStream(); InputStream inStream = btSocket.getInputStream(); Use the input stream to read data from the remote device. Use the output stream to write data to the remote device. Use reader/writer filters if performing text I/O. PrintWriter out = new PrintWriter( new OutputStreamWriter(outStream)); BufferedReader in = new BufferedReader( new InputStreamReader(inStream)); Slide 27©SoftMoore Consulting

28 Example: Programming the Server private class AcceptThread extends Thread { private final BluetoothServerSocket btServerSocket; public AcceptThread() { // Use a temporary object that is later assigned to // btServerSocket since btServerSocket is final BluetoothServerSocket tempServerSocket = null; try { tempServerSocket = bluetoothAdapter. listenUsingRfcommWithServiceRecord(NAME, UUID); } catch (IOException e) { Log.e(DEBUG_TAG, "AcceptThread not created", ex); } btServerSocket = tempServerSocket; } Slide 28©SoftMoore Consulting

29 Example: Programming the Server (continued) public void run() { BluetoothSocket socket = null; // Keep listening until socket is returned or exception while (true) { try { socket = btServerSocket.accept(); } catch (IOException e) { Log.e(DEBUG_TAG, "ServerSocket.accept()", ex); break; } Slide 29©SoftMoore Consulting

30 Example: Programming the Server (continued) if (socket != null) { // Manage the connection (in a separate thread) manageConnectedSocket(socket); btServerSocket.close(); break; } } } /** Cancel listening socket and cause the thread to finish */ public void cancel() { try { byServerSocket.close(); } catch (IOException e) {... } } } Slide 30©SoftMoore Consulting

31 Connecting Bluetooth Devices: Programming the Client Obtain a remote device; e.g., through device discovery or by querying the adapter to get the set of previously paired devices. Use the device to get a BluetoothSocket by calling createRfcommSocketToServiceRecord(UUID). The UUID must match the UUID used by the server. –declare the UUID string as a constant in the application –reference it from both the server and client code Initiate the connection by calling connect(). If the remote device accepts the connection, it will share the RFCOMM channel to use during the connection and connect() will return. Slide 31©SoftMoore Consulting

32 Connecting Bluetooth Devices: Programming the Client (continued) Method connect() method is a blocking call. –must be called on a non-UI thread –method times out after about 12 seconds – throws an exception Slide 32©SoftMoore Consulting Note: The device should not be performing discovery when connect() is called. If discovery is in progress, then the connection attempt will be significantly slower and is more likely to fail.

33 Relevant Links Bluetooth http://developer.android.com/guide/topics/connectivity/bluetooth.html BluetoothChat \samples\ \legacy\BluetoothChat Bluetooth (Wikipedia) http://en.wikipedia.org/wiki/Bluetooth Slide 33©SoftMoore Consulting


Download ppt "Bluetooth. Bluetooth is an open, wireless protocol for exchanging data between devices over a short distance. –managed by the Bluetooth Special Interest."

Similar presentations


Ads by Google