Presentation is loading. Please wait.

Presentation is loading. Please wait.

Bluetooth.

Similar presentations


Presentation on theme: "Bluetooth."— Presentation transcript:

1 Bluetooth

2 Bluetooth 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 , 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 ©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 exchanging 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 ©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 Both permissions are designated as “normal” permissions; i.e., not dangerous. ©SoftMoore Consulting

5 Example: Bluetooth Permissions
<manifest ... > <uses-permission android:name="android.permission.BLUETOOTH"/> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/> ... </manifest> ©SoftMoore Consulting

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

7 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 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). ©SoftMoore Consulting

8 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 ... } 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(); ©SoftMoore Consulting

9 Setting Up 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(). ©SoftMoore Consulting

10 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); } ©SoftMoore Consulting

11 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, then the activity receives result code RESULT_OK in the onActivityResult() callback. If the user responds “DENY” or if Bluetooth was not enabled due to an error, then the activity receives result code is RESULT_CANCELED in the onActivityResult() callback. ©SoftMoore Consulting

12 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. ©SoftMoore Consulting

13 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. ©SoftMoore Consulting

14 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(). ©SoftMoore Consulting

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

16 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. ©SoftMoore Consulting

17 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. 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. ©SoftMoore Consulting

18 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. ©SoftMoore Consulting

19 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 ©SoftMoore Consulting

20 Example: Create a Broadcast Receiver
// defined as an instance variable for the activity private HashMap<String, BluetoothDevice> discoveredDevices = new HashMap<>(); // defined as an inner class within the activity private class BluetoothBroadcastReceiver extends BroadcastReceiver 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); } ©SoftMoore Consulting

21 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" } Note: You also can register the broadcast receiver to receive other events; e.g., BluetoothAdapter.ACTION_STATE_CHANGED. ©SoftMoore Consulting

22 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. ©SoftMoore Consulting

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

24 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 (1) sends request to server for data (4) displays data and responds to user input Server listens for connection requests from clients (2) receives request from client (3) formulates response and sends response to client Difference between client and server is relative. It’s just peers talking to each other. ©SoftMoore Consulting

25 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: a-f2e8-475a d6c36fa7 ©SoftMoore Consulting

26 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 ©SoftMoore Consulting

27 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. ©SoftMoore Consulting

28 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)); ©SoftMoore Consulting

29 Example: Programming the Server
private class AcceptThread extends Thread { private final BluetoothServerSocket btServerSocket; public AcceptThread() { BluetoothServerSocket tempServerSocket = null; try { tempServerSocket = bluetoothAdapter. listenUsingRfcommWithServiceRecord(NAME, UUID); } catch (IOException e) { Log.e(DEBUG_TAG, "AcceptThread not created", ex); } btServerSocket = tempServerSocket; } (continued on next page) ©SoftMoore Consulting

30 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; } (continued on next page) ©SoftMoore Consulting

31 Example: Programming the Server (continued)
if (socket != null) { // Manage the connection in a separate thread manageConnectedSocket(socket); btServerSocket.close(); break; } } } (continued on next page) ©SoftMoore Consulting

32 Example: Programming the Server (continued)
/** * Cancel listening socket and cause thread to finish */ public void cancel() { try { byServerSocket.close(); } catch (IOException e) { ... } } } ©SoftMoore Consulting

33 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. ©SoftMoore Consulting

34 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 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. ©SoftMoore Consulting

35 Relevant Links Bluetooth Bluetooth Low Energy
Bluetooth Low Energy Android – Bluetooth (Tutorials Point) BluetoothChat Bluetooth (Wikipedia) ©SoftMoore Consulting


Download ppt "Bluetooth."

Similar presentations


Ads by Google