Android Developer--Bluetooth Chapter two development examples

Source: Internet
Author: User
Tags uuid

Connecting devices

In order to create a connection between your application on both devices, you must implement both the Server-side and Clien T-side mechanisms, because one device must open a server socket and the other one must initiate the connection (using the Server device ' s MAC address to initiate a connection. The server and client is considered connected to all other when they has a connected on the BluetoothSocket same RFCOMM Chan Nel. At here, each device can obtain input and output streams and data transfer can begin, which are discussed in the sect Ion about managing a Connection. This sections describes how to initiate the connection between the devices.

The server device and the client device each obtain the required in BluetoothSocket different ways. The server would receive it when a incoming connection is accepted. The client would receive it when it opens a RFCOMM channel to the server.

One implementation technique is to automatically prepare all device as a server, so this one has a server socket ope N and listening for connections. Then either device can initiate a connection with the other and become the client. Alternatively, one device can explicitly "host" the connection and open a server socket on demand and the other device can Simply initiate the connection.

To create a connection between two devices, the application must implement both the server and client mechanisms. Because a device on one end must open the server socket, the other end must initialize a connection (by using the server device's MAC address to initialize the connection). When the server and the client are connected to each other, they will each have a connection on the same Rfcomm channel BluetoothSocket . Each device contains an input/output stream for data exchange, as detailed in the Managing a connection section. This section discusses how to initialize a connection between two devices.

The server appliance and the client device each obtain the required bluetoothsocket in different ways. When the receive connection is accepted, the server receives it. When it opens a Rfcomm channel to the server, the customer will receive it.

One implementation technique is that each device acts as a server so that it can have a server socket to listen for connections. When the other device initializes the connection, it becomes the client. In addition, when the device becomes "host", it will open a server socket and the other devices will simply connect.

Note:if the devices has not been previously paired and then the Android framework would automatically show a pairing req Uest notification or dialog to the user during the connection procedure, as shown in Figure 3. So when attempting to connect devices, your application does not need to being concerned about whether or not the devices is Paired. Your RFCOMM connection attempt would block until the user has successfully paired, or would fail if the user rejects pairing , or if pairing fails or times out.

Note: If these two devices have never been paired before, then the Android framework will automatically display a pairing request notification during the connection process, or dialog. Therefore, when you try to connect to a device, your application does not need to be concerned about whether the device is paired. Your Rfcomm connection attempt will block until the user is successfully paired, or if the user rejects the pairing failure, or the pairing timeout fails. ---is to connect, you can prompt the match.

connecting as a server

When you want to connect the devices, one must act as a server by holding an open BluetoothServerSocket . The purpose of the server socket is to listen for incoming connection requests and when one is accepted, provide a connect Ed BluetoothSocket . When BluetoothSocket BluetoothServerSocket the was acquired from the, the BluetoothServerSocket can (and should) being discarded, unless you want to accept more connect Ions.

When you want to connect two devices, one end must work in the server state and have an open bluetoothserversocket. The purpose is to listen for incoming connection requests, and once the request is accepted, provide one BluetoothSocket . When BluetoothSocket从BluetoothServerSocket获取的时候,BluetoothServerSocket可以(应该)被舍弃,除非你想要更多的连接。

Here's the basic procedure to set up a server socket and accept a connection:

  1. Get a  bluetoothserversocket  by calling the  Listenusingrfcommwithservicerecord (String, UUID) .

    The string is an identifiable name of your service, which the system would automatically write to a new service Discover Y Protocol (SDP) database entry on the device (the name was arbitrary and can simply be your application name). The UUID is also included in the SDP entry and would be the basis for the connection Agreement with the client device. That's, when the client attempts to connect with this device, it'll carry a UUID that uniquely identifies the service W ith which it wants to connect. These uuids must match in order for the connection to is accepted (in the next step).

  2. Start listening for connection requests by CALLING  accept () .

    This was a blocking call. It would return when either a connection have been accepted or an exception have occurred. A connection is accepted if a remote device has sent a connection request with a UUID matching the one registered W ITH this listening server socket. When successful,  accept ()  will return a connected  bluetoothsocket .

  3. Unless want to accept the additional connections, call close() .

    This releases the server sockets and all their resources, but does not close the connected that BluetoothSocket ' s been returne D 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 on the BluetoothServerSocket immediately after accepting a connected socket.

Here is the basic procedure that shows how to set up a server socket and accept a connection:

Steps:

The first step:

1. By calling listenUsingRfcommWithServiceRecord(String, UUID) . To getBluetoothServerSocket。参数String是你服务的名称,系统会自动的写入一个新的 new Service Discovery Protocol (SDP) database entry(该名字可以是任意的,简单写应用程序名就行。) UUID也包括在SDP entry并将成为客户设备的连接协议的基础。它将携带一个UUID用来唯一标识它要连接的服务。这些UUID必须匹配,为了连接能被接受(下一步)。

Step Two:

2. Call accept() the. method to begin listening for connection requests.

This is a blocking method that will return when the connection is accepted or an exception occurs. The remote device needs to carry the UUID to connect to the server socket. If successful, a connected is returned BluetoothSocket .

Step Three:

3. Call the. Method unless you want to accept more connections close() .

This method frees the server socket and all the resources it occupies, but it does not close the connected bluetoothsocket. Unlike TCP/IP, RFCOMM allows only one connected client per channel at a time, so in most cases it makes sense to call the close () method immediately after accepting a connected socket.

The call should isn't being executed in the accept() main Activity UI thread because it's a blocking call and would prevent any OT Her interaction with the application. It usually makes sense to does all work with a BluetoothServerSocket or in BluetoothSocket a new thread managed by your application. To abort a blocked call such accept() as, call on the close() BluetoothServerSocket (or BluetoothSocket ) from another thread and the blocked call would im mediately return. Note that any methods on a BluetoothServerSocket or is BluetoothSocket thread-safe.

accept()method should not be called in the main thread, because it is a blocking method. So another thread is required to process BluetoothServerSocket or BluetoothSocket .

Example

Here's a simplified thread for the server component that accepts incoming connections:

Private classConnectthreadextendsThread {Private FinalBluetoothsocket Mmsocket; Private FinalBluetoothdevice Mmdevice;  PublicConnectthread (Bluetoothdevice device) {//Use a temporary object, which is later assigned to Mmsocket,//because Mmsocket is finalBluetoothsocket tmp =NULL; Mmdevice=device; //Get a bluetoothsocket to connect with the given Bluetoothdevice        Try {            //My_uuid is the app's UUID string, also used by the server codeTMP =Device.createrfcommsockettoservicerecord (MY_UUID); } Catch(IOException e) {} Mmsocket=tmp; }      Public voidrun () {//Cancel Discovery because it'll slow down the connectionMbluetoothadapter.canceldiscovery (); Try {            //Connect the device through the socket. this would block//until it succeeds or throws an exceptionMmsocket.connect (); } Catch(IOException connectexception) {//Unable to connect, close the socket and get out            Try{mmsocket.close (); } Catch(IOException closeexception) {}return; }         //Do work to manage the connection (in a separate thread)Manageconnectedsocket (Mmsocket); }     /**Would cancel an in-progress connection, and close the socket*/     Public voidCancel () {Try{mmsocket.close (); } Catch(IOException e) {} }}

Notice that's cancelDiscovery() called before the connection is made. You should always does this before connecting and it's safe to call without actually checking whether it's running or not Want to check, call isDiscovering() ).

manageConnectedSocket()is a fictional method in the application that would initiate the thread for transferring data, which are discussed in the SE Ction about managing a Connection.

When you ' re do with your BluetoothSocket close() . Doing so would immediately close the connected socket and clean up all internal resources.

Note: The canceldiscovery () method needs to be called when connecting the device. When you connect, you always have to do it. Moreover, this method is secure, regardless of whether it is running (call the isdiscovering () method if it needs to be confirmed).

Manageconnectedsocket () is a fictitious method used to initialize the thread of the interchange data, described in detail in managing a Connection.

When you're done with it, BluetoothSocket always call close () to clean it up. Doing so will immediately close the connected sockets and clean up all internal resources.

Android Developer--Bluetooth Chapter two development examples

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.