Example of Bluetooth client-side and server-side communication with Android

1、 First of all, Bluetooth communication must be tested by mobile phone, because there is no relevant hardware in AVD, and an error will be reported!

OK, look at the final rendering:

2、 Overview:

1. Determine whether Bluetooth is supported

2. If supported, open Bluetooth

3. Monitor Bluetooth on status

4. Set that the local device can be searched by other devices

5. Search device

Start searching bluetoothadapter. Startdiscovery();

Stop searching bluetoothadapter. Canceldiscovery();

When a device is found, the system will issue an action_ Based on the found broadcast message, we can implement the broadcastreceiver that receives this message

6. Connecting equipment

To connect two Bluetooth devices, the server (Bluetooth server socket) and the client (Bluetooth socket) should be implemented respectively, which is the same as that in J2SE

ServerSocket is very similar to socket.

The bluetoothserversocket calls the accept () method on the server side to listen. When a client request arrives, the accept () method returns the bluetoothsocket. After the client gets it, the two ends can communicate. Data transmission is realized through InputStream and OutputStream.

The accept method is blocked, so it cannot be placed in the UI thread. When Bluetooth ServerSocket and Bluetooth socket are used, they are usually placed in their own new threads.

3、 How

Here are some key steps in development:

1) Turn on Bluetooth first

2) Search for available devices

3) Create a Bluetooth socket and obtain the input / output stream

4) Read and write data

5) Disconnect and turn off Bluetooth

1. Because there is page switching, I use tabhost here, but the original effect is not good and there is no animation, so I have to copy it myself

2. First set up the home page and use the copied tabhost to slide. There are three states according to the state

3. With the home page, you can start to implement two list pages respectively, one is the find device page deviceactivity.java, and the other is the session page chatactivity.java

1) Device page deviceactivity.java

2) Session page chatactivity.java

3、 Relevant code download

Demo download: http://xiazai.jb51.net/201701/yuanma/App_ BlueTooth_ jb51.rar

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>