bluetooth. bluetooth is an open, wireless protocol for exchanging data between devices over a short...

33
Bluetooth

Upload: william-rose

Post on 24-Dec-2015

237 views

Category:

Documents


2 download

TRANSCRIPT

Bluetooth

©SoftMoore Consulting

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 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

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

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<manifest ... >  <uses-permission android:name ="android.permission.BLUETOOTH" />  <uses-permission android:name ="android.permission.BLUETOOTH_ADMIN" />  ...</manifest>

Slide 4

©SoftMoore Consulting

Four Major Tasks forCommunicating 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

Setting Up Bluetooth:Get a BluetoothAdapter

• Import the Bluetooth packageimport 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

Note: The question of whether or not a device has aBluetooth adapter is separate for the question of whetheror not the Bluetooth adapter is turned on (enabled).

©SoftMoore Consulting

Example: Get a BluetoothAdapter

// defined as an instance variableprivate BluetoothAdapter bluetoothAdapter;

// in the activity's onCreate() methodbluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

if (bluetoothAdapter == null) { // device does not have a bluetooth adapter ... }

Slide 7

For Android API levels 17 and higher, the following code canalso be used to obtain a Bluetooth adapter:BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);bluetoothAdapter = bluetoothManager.getAdapter();

©SoftMoore Consulting

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

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 methodif (!bluetoothAdapter.isEnabled()) {    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); }

Slide 9

©SoftMoore Consulting

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

Example: Enable Bluetooth(continued)

@Overrideprotected 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

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

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

Example: Obtaining the Set of Bonded Devices

Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();

for (BluetoothDevice device : pairedDevices) { ...  }

Slide 14

©SoftMoore Consulting

Difference Between Being Pairedand 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

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

Note: Android-powered devices are not discoverable bydefault. A user can make the device discoverable for alimited time through the system settings, or an applicationcan request that the user enable discoverability.

©SoftMoore Consulting

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

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

Example: Create a Broadcast Receiver

// defined as an instance variable for the activityprivate HashMap<String, BluetoothDevice> discoveredDevices = new HashMap<String, BluetoothDevice>();

// defined as an inner class within the activitiyprivate 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

Example: Register the Broadcast Receiver

// defined as an instance variable for the activityprivate BluetoothBroadcastReceiver receiver;

// in the activity's onCreate() methodreceiver = new BluetoothBroadcastReceiver(); IntentFilter actionFoundFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);registerReceiver(receiver, actionFoundFilter); if (bluetoothAdapter.startDiscovery()) { ... // show Toast "Bluetooth discovery started" }

Slide 20

Note: You also can register the broadcast receiver to receive otherevents; e.g., BluetoothAdapter.ACTION_STATE_CHANGED.

©SoftMoore Consulting

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

Enabling Discovery(continued)

Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);discoverableIntent.putExtra (BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 200);startActivity(discoverableIntent);

Slide 22

©SoftMoore Consulting

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

Difference between client and server isrelative. It’s just peers talking to each other.

©SoftMoore Consulting

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

• ExampleSystem.out.println(UUID.randomUUID());

Output: 3964633a-f2e8-475a-9642-7805d6c36fa7

Slide 24

©SoftMoore Consulting

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

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

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

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

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

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

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

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

Note: The device should not be performing discoverywhen connect() is called. If discovery is in progress,then the connection attempt will be significantly slowerand is more likely to fail.

©SoftMoore Consulting

Relevant Links

• Bluetoothhttp://developer.android.com/guide/topics/connectivity/bluetooth.html

• BluetoothChat<ANDROID_SDK_HOME>\samples\<API_LEVEL>\legacy\

BluetoothChat

• Bluetooth (Wikipedia)http://en.wikipedia.org/wiki/Bluetooth

Slide 33