Two ways to connect to a Bluetooth

Source: Internet
Author: User
Tags manage connection

In order to create a connection between the two devices, the server-side and client mechanisms must be implemented because one device must open a server Socket and the other must initiate a connection (using the server-side device's MAC address to initiate the connection). When both the server side and the client have a bluetoothsocket on the same Rfcomm channel, the connections are established on both sides. At this point, each device can get an input and output stream for data transfer.
The way the server side and the client get Bluetoothsocket is different, and the server side is a bluetoothsocket when the client connection is accepted. The client gets bluetoothsocket when it opens a Rfcomm channel to the server side.
One implementation technique for Bluetooth connectivity is that each device is automatically prepared as a server, so each device has a server socket and listens for connections. Each device can then establish a connection to another device as a client.
Another alternative is that one device opens a server Socket on demand, and another device only establishes a connection to the device as a client.

1. Connect as a server
if you want to connect two devices, one of them must act as a server and it has bluetoothserversocket. The role of the server socket is to listen for incoming connections and return a Bluetoothsocket object when a connection is accepted. After acquiring the Bluetoothsocket object from Bluetoothserversocket, the Bluetoothserversocket can (and should) be discarded, unless it is also used to receive more connections.
The following are the basic steps for establishing a server socket and accepting a connection:
Step 1 by calling Listenusingrfcommwithservicerecord (String, UUID) method to get a Bluetoothserversocket object. The string parameter is the identity name of the service, and the name is arbitrary and can simply be the name of the application. When the client attempts to connect to the device, it will carry a UUID that uniquely identifies the service it is connecting to, the UUID must match, and the connection will be accepted.
Step 2 listens for connection requests by calling accept (). This is a blocking thread that will not return until a connection is accepted or an exception is generated. The connection request is accepted when the client carries a UUID that matches the UUID that listens to its socket registration. If successful, accept () returns a Bluetoothsocket object.
Step 3 Call Close () unless you need to accept another connection. Close () frees the server socket and its resources, but does not close the Bluetoothsocket object returned by the Accept (). Unlike TCP/IP, Rfcomm a channel allows only one client connection at a time, so most cases mean that close () should be called immediately after Bluetoothserversocket accepts a connection request. The
Accept () call should not be made in the main activity UI thread because it is a blocking thread that interferes with other interactions in the app. It is common to do all the work of Bluetoothserversocket or bluetoothsocket in a new thread to avoid thread blocking. If you need to discard the blocking thread, you can call the close () method.
The following is an example of a thread that accepts connections for a server component.

Define accept thread Private class Acceptthread extends thread {//Create Bluetoothserversocket class private final Bluetoothserversocket Mmserversocket;public Acceptthread () {bluetoothserversocket tmp = null;try {//my_uuid is the app's UUID ID tmp = Mbluetoothadapter.listenusingrfcommwithservicerecord (NAME, my_uuid);} catch (IOException e) {}mmserversocket = tmp;}  The thread starts when the public void run () {Bluetoothsocket socket = null;//remains listening while (true) {try {//accepts socket = Mmserversocket.accept ();} catch (IOException e) {break;} Connection accepted if (socket!=null) {//Manage connection manageconnectedsocket (socket);//close connection mmserversocket.close (); break;}}} Close connection public void Cancel () {try{//close bluetoothserversocketmmserversocket.close ();} catch (IOException e) {}}}

In this case, only one incoming connection is accepted, once the connection is accepted and the Bluetoothsocket is received, the application sends the obtained bluetoothsocket to a separate thread, then closes the bluetoothserversocket and jumps out of the loop.
---------------------
note that when accept () returns Bluetoothsocket, the socket establishes a connection, so you should not call Connect () on the client.
---------------------

2. Connect as a client

To achieve a connection to a remote server device, you must first obtain an object that represents the remote device Bluetoothdevice. Then use the Bluetoothdevice object to obtain a bluetoothsocket to implement the connection.
The basic steps are as follows:
Step 1 uses Bluetoothdevice to call the method Createrfcommsockettoservicerecord (UUID) to get a Bluetoothsocket object.
Step 2 Call Connect () to establish the connection. When this method is called, the system completes an SDP lookup on the remote device to match the UUID. If the lookup succeeds and the remote device accepts the connection, the Rfcomm channel is shared, and connect () returns. This method is also a blocking call. If the connection fails or the timeout (12 seconds) throws an exception.
---------------------
note to ensure that no device search is made when you call Connect (), if you are searching for a device, the connection attempt is significantly slower and the connection is likely to fail.
---------------------
The following is an example of a thread that initiates a Bluetooth connection.

Define a Bluetooth connection thread private class Connectthread extends thread {//New Bluetoothsocket class private final Bluetoothsocket mmsocket;//new Bluetoothdevice Object Private final Bluetoothdevice mmdevice;public Connectthread (Bluetoothdevice device) { Bluetoothsocket tmp = null;//assignment to device Mmdevice = device;try {//Create and return a bluetoothsockettmp based on the UUID = Device.createrfcommsockettoservicerecord (MY_UUID);} catch (IOException e) {}//assigned to Bluetoothsocketmmsocket = tmp;} public void Run () {//de-Discovery Device mbluetoothadapter.canceldiscovery (); try {//Connect to Device Mmsocket.connect ();} catch (IOException Connectexception) {//cannot connect, close Sockettry{mmsocket.close ();} catch (IOException connectexception) {}return;} Manage Connection Manageconnectedsocket (Mmsocket);} Cancel connection public void Cancel () {try{//close bluetoothsocketmmsocket.close ();} catch (IOException e) {}}}

Note : Canceldiscovery () is called before the connection operation is applied. Before connecting, regardless of whether the search has been performed. The call is secure and does not require confirmation (of course, you can call the Isdiscovering () method if you want to confirm). When you're done, don't forget to call the close () method to close the connected socket and release all internal resources.

3. Managing Connections

If two devices have successfully established a connection, each will have a bluetoothsocket, and the data can be shared between devices. With Bluetoothsocket, it is usually easier to transfer any data, usually as follows:
+ get input and output streams using getInputStream () and Getoutputstream () respectively to process the transfer.
+ Call Read (byte[]) and write (byte[]) for data reading and writing.
Of course, pay attention to some implementation details. For example, a dedicated thread is required to read and write the stream, because methods read (byte[]) and write (byte[]) are blocking calls. Read (byte[]) blocks until data is readable in the stream. Write (byte[]) is usually not blocked, but if the remote device calls read (byte[]) is not fast enough to cause an intermediate buffer to be full, it may also block. So the main loop in the thread should be used to read InputStream. There should also be a separate method for writing outputstream in the thread.
Take a look at the following example:

Connection management thread Private class Connectthread extends thread {//New Bluetoothsocket class private final Bluetoothsocket mmsocket;// New input Stream object private final InputStream mminstream;//new output stream object private final OutputStream mmoutstream;public Connectthread ( Bluetoothsocket socket) {//Assign initial value to Bluetoothsocket mmsocket = socket;//input stream assigned to Nullinputstream Tmpin = null;// The output stream is assigned a value of nulloutputstream Tmpout = null;try {//Gets the input stream from Bluetoothsocket Tmpin = Socket.getinputstream ();// Get output stream from Bluetoothsocket tmpout = Socket.getoutputstream ();} catch (IOException e) {}//assigns a value to the input stream mminstream = temin;//assigns a value to the output stream mmoutstream = Temout;} public void Run () {//Stream buffer size byte[] buffer = new byte[1024];//is used to save read () reads the number of bytes int Bytes;while (true) {try{// Read data from the input stream bytes = mminstream.read (buffer);//Send data to Interface mhandler.obtainmessage (Message_read, Bytes,-1, buffer). Sendtotarget ();} catch () {break;}}} Send data to remote device public void write (byte[] bytes) {try{//writes data to the output stream Mmoutstream.write (bytes);} catch (IOException e) {}}//cancels public void cancel () {try{//closes B connection Mmsocket.close ();} catch (IOException e) {}}} 

The constructor gets the required stream, and once executed, the thread waits for data from InputStream, and when read (byte[]) returns the bytes read from the stream, the data is sent to the primary activity through the member handler of the parent class, and then continues to wait for the data in the stream to be read. Sending data outward simply calls the thread's write () method. The Cancel () method of the thread is important so that the connection can be terminated at any time by closing the bluetoothsocket. It is always called after the Bluetooth connection has been processed.

Two ways to connect to a Bluetooth

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.