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

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
Remote Procedure Call (RPC)
CCNA – Network Fundamentals
Text File I/O. Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with an editor are called.
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.
CEG3185 Tutorial 4 Prepared by Zhenxia Zhang Revised by Jiying Zhao (2015w)
TCP Sockets Reliable Communication. TCP As mentioned before, TCP sits on top of other layers (IP, hardware) and implements Reliability In-order delivery.
Io package as Java’s basic I/O system continue’d.
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.
FTP (File Transfer Protocol) & Telnet
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
CSS216 MOBILE PROGRAMMING Android, Chapter 13 Book: “Professional Android™ 2 Application Development” by Reto Meier, 2010 by: Andrey Bogdanchikov (
Networking: Part 2 (Accessing the Internet). The UI Thread When an application is launched, the system creates a “main” UI thread responsible for handling.
Data Storage: Part 4 (Content Providers). Content Providers Content providers allow the sharing of data between applications. Inter-process communication.
School of Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae, VUW Networking COMP # 21.
J2EE Structure & Definitions Catie Welsh CSE 432
Cli/Serv.: Chat/121 Client/Server Distributed Systems v Objectives –discuss a client/server based chat system –mention two other ways of chatting.
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.
Internet Applications and Network Programming Dr. Abraham Professor UTPA.
School of Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae david streader, VUW Echo Networking COMP
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
Practicum: - Client-Server Computing in Java Fundamental Data Structures and Algorithms Margaret Reid-Miller 13 April 2004.
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.
Lecture 9 Network programming. Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the Internet.
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.
Cosc 5/4730 Android Communications Intents, callbacks, and setters.
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.
1 Chapter 28 Networking. 2 Objectives F To comprehend socket-based communication in Java (§28.2). F To understand client/server computing (§28.2). F To.
Networks Sockets and Streams. TCP/IP in action server ports …65535 lower port numbers ( ) are reserved port echo7 time13 ftp20 telnet23.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Applications with Multiple Activities. Most applications will have more than one activity. The main activity is started when the application is started.
GPRS functionality overview in Horner OCS. GPRS functionality – Peer to Peer communication over GPRS – CSCAPE connectivity over GPRS – Data exchange using.
Introducing Intents Intents Bind application components and navigate between them Transform device into collection of interconnected systems Creating a.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
©SoftMoore ConsultingSlide 1 Overview of Servlets and JavaServer Pages (JSP)
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 ( 李德成 )
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.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
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.
School of Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae david streader, VUW Echo Networking COMP
Object-Orientated Analysis, Design and Programming
Permissions.
Intents and Broadcast Receivers
Threads in Java Two ways to start a thread
Bluetooth.
Instructor: Mazhar Hussain
MCA – 405 Elective –I (A) Java Programming & Technology
Wireless Communication between Android Application and Sensors
Clients and Servers 19-Nov-18.
Clients and Servers 1-Dec-18.
Android Developer Fundamentals V2 Lesson 5
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 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 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 <uses-permission android:name ="android.permission.BLUETOOTH" /> <uses-permission android:name ="android.permission.BLUETOOTH_ADMIN" />... Slide 4©SoftMoore Consulting

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

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

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();

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 method if (!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 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

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 pairedDevices = bluetoothAdapter.getBondedDevices(); for (BluetoothDevice device : pairedDevices) {... } Slide 14©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. 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©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.

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 activity private HashMap discoveredDevices = new HashMap (); // defined as an inner class within the activitiy 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); } Slide 19©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" } Slide 20©SoftMoore Consulting Note: You also can register the broadcast receiver to receive other events; e.g., BluetoothAdapter.ACTION_STATE_CHANGED.

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©SoftMoore Consulting Difference between client and server is relative. It’s just peers talking to each other.

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

Relevant Links Bluetooth BluetoothChat \samples\ \legacy\BluetoothChat Bluetooth (Wikipedia) Slide 33©SoftMoore Consulting