Bluetooth.

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
1 Chapter 12 Working With Access 2000 on the Internet.
1 Java Networking – Part I CS , Spring 2008/9.
WECPP1 Java networking Jim Briggs based on notes by Amanda Peart based on Bell & Parr's bonus chapter
Network Programming CS3250. References Core Java, Vol. II, Chapter 3. Book examples are available from
© Lethbridge/Laganière 2001 Chap. 3: Basing Development on Reusable Technology 1 Let’s get started. Let’s start by selecting an architecture from among.
1 CMSC628: Introduction to Mobile Computing Nilanjan Banerjee Mobile Systems Programming (Acknowledgment to Deepa Shinde and Cindy Atheron University of.
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)
2011 Embedded Systems Software Training Center BluRapport SDK.
NET0183 Networks and Communications Lecture 31 The Socket API 8/25/20091 NET0183 Networks and Communications by Dr Andy Brooks Lecture powerpoints from.
CSS216 MOBILE PROGRAMMING Android, Chapter 13 Book: “Professional Android™ 2 Application Development” by Reto Meier, 2010 by: Andrey Bogdanchikov (
Google Cloud Messaging for Android (GCM) is a free service that helps developers send data from servers to their Android.
HTTP HTTP stands for Hypertext Transfer Protocol. It is an TCP/IP based communication protocol which is used to deliver virtually all files and other.
Networking: Part 2 (Accessing the Internet). The UI Thread When an application is launched, the system creates a “main” UI thread responsible for handling.
School of Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae, VUW Networking COMP # 21.
1 Announcements Homework #2 due Feb 7 at 1:30pm Submit the entire Eclipse project in Blackboard Please fill out the when2meets when your Project Manager.
J2EE Structure & Definitions Catie Welsh CSE 432
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.
1 Streams Files are a computer’s long term memory Need ability for programs to –get information from files –copy information from program variables to.
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.
Linking Activities using Intents How to navigate between Android Activities 1Linking Activities using Intents.
© Lethbridge/Laganière 2005 Chap. 3: Basing Development on Reusable Technology The Client-Server Architecture A distributed system is a system in.
Networks Sockets and Streams. TCP/IP in action server ports …65535 lower port numbers ( ) are reserved port echo7 time13 ftp20 telnet23.
Applications with Multiple Activities. Most applications will have more than one activity. The main activity is started when the application is started.
Introducing Intents Intents Bind application components and navigate between them Transform device into collection of interconnected systems Creating a.
Prepared by Dr. Jiying Zhao University of Ottawa Canada.
UNIT-6. Basics of Networking TCP/IP Sockets Simple Client Server program Multiple clients Sending file from Server to Client Parallel search server.
1 Lecture 9: Network programming. 2 Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Lecture 2: Android Concepts
Agenda Socket Programming The OSI reference Model The OSI protocol stack Sockets Ports Java classes for sockets Input stream and.
Technische Universität München Services, IPC and RPC Gökhan Yilmaz, Benedikt Brück.
Intents and Broadcast Receivers Dr. David Janzen Except as otherwise noted, the content of this presentation is licensed under the Creative Commons Attribution.
Messaging and Networking. Objectives Send SMS messages using the Messaging app Send SMS messages programmatically from within your app Receive and consume.
Developing Android Services. Objectives Creating a service that runs in background Performing long-running tasks in a separate thread Performing repeated.
Presenter: Tyler Newsome
Chapter Objectives In this chapter, you will learn:
Object-Orientated Analysis, Design and Programming
Permissions.
Intents and Broadcast Receivers
Lecture 2: Android Concepts
Echo Networking COMP
Threads in Java Two ways to start a thread
Broadcast receivers.
CS371m - Mobile Computing Services and Broadcast Receivers
Linking Activities using Intents
Instructor: Mazhar Hussain
Networking COMP
MCA – 405 Elective –I (A) Java Programming & Technology
Client-server Programming
Lecture 12: Bluetooth LE Topics: BLE Basics, code example.
Reactive Android Development
Unit 27 - Web Server Scripting
Developing Android Services
Wireless Communication between Android Application and Sensors
Clients and Servers 19-Nov-18.
Clients and Servers 1-Dec-18.
Units with – James tedder
Android Topics Asynchronous Callsbacks
Activities and Intents
Android Developer Fundamentals V2 Lesson 5
Lecture 12: Bluetooth LE Topics: BLE Basics, code example.
Mobile Programming Dr. Mohsin Ali Memon.
Clients and Servers 19-Jul-19.
Clients and Servers 13-Sep-19.
Exceptions and networking
Presentation transcript:

Bluetooth

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Enabling Discovery (continued) Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableIntent.putExtra (BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 200); startActivity(discoverableIntent); ©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 (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

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

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

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

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

Example: Programming the Server (continued) /** * Cancel listening socket and cause thread to finish */ public void cancel() { try { byServerSocket.close(); } catch (IOException e) { ... } } } ©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. ©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 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

Relevant Links Bluetooth Bluetooth Low Energy https://developer.android.com/guide/topics/connectivity/bluetooth.html Bluetooth Low Energy https://developer.android.com/guide/topics/connectivity/bluetooth-le.html Android – Bluetooth (Tutorials Point) https://www.tutorialspoint.com/android/android_bluetooth.htm BluetoothChat https://developer.android.com/samples/BluetoothChat/index.html Bluetooth (Wikipedia) https://en.wikipedia.org/wiki/Bluetooth ©SoftMoore Consulting