From: http://www.52solution.com/article/articleinfo/id/80009971/page/1
Central topics:
* Development of Bluetooth on Android
1. Overview
Bluetooth is a standard feature of almost every mobile phone. It is mostly used for connection between devices such as headphones MIC and mobile phones. In addition, Bluetooth communication can be established between multiple mobile phones, this article introduces the development of Bluetooth on Android through a chat room routine in the SDK.
When android1.x is used, the related APIs are very incomplete and cannot be simply developed using Bluetooth. There is an open-source project that can help programmers use and develop Bluetooth and support direct methods of the Bluetooth protocol stack. After Android 2, the Framework provides some official APIs for Bluetooth communication, but the current program is not complete. This article mainly discusses how to use the Bluetooth communication API after android2.
First look at the chat room:
2. Bluetooth communication API Introduction
2.1. Bluetooth communication process
2.2. Main Methods of Bluetooth API
Bluetoothadapter class
Descrithadapter. getdefaadapter adapter (): obtains the local default descrithadapter. If the return value is null, Bluetooth is not supported locally;
Isdiscovering (): returns whether the device is discovering a bluetooth device;
Canceldiscovery (): cancels the process of discovering a remote Bluetooth device;
Startdiscovery (): starts the discovery process;
Getscanmode (): Get the scan mode of the local Bluetooth device;
Getbondeddevices (): gets the paired device;
IsEnabled (): whether to enable the Bluetooth function.
When the Bluetooth function is not enabled, call the following settings to enable Bluetooth:
If you find that the current device has not enabled the external visibility mode, you can pass the Intent to call the method to enable the discoverable mode. The Code is as follows:
Which is the corresponding remote Bluetooth Device.
CreateRfcommSocketToServiceRecord (): Create the socket of the Device.
BluetoothSocket class
Connect (): request to connect to Bluetooth.
GetInputStream (): gets the input stream, used to receive remote information.
GetOutputStream (): Get the output stream and send it to the remote party.
Close (): Disable the Bluetooth connection.
InputStream class:
Read (byte []): read the input stream in blocking mode.
OutputStream class:
Write (byte []): write information to the output stream and send it to a remote device.
3. Analyze thchat routine
The routine for Bluetooth development provided by Google is javasthchat. You can see this document at the beginning. In addition to configuration and ui definition files, the main program file contains three: BluetoothChat. java, BluetoothChatService. java, and DeviceListActivity. java. The detailed functions are described below.
3.1. Overall call relationship sequence diagram
3.2. javasthchat. java
Main activity of the routine. Oncreate () to obtain the local thadapter device and check whether it is supported. In onstart (), check whether Bluetooth is enabled and request to be enabled. Then, execute setupchat () and setupchat () to initialize the control in the interface and add a click listener. Then, create the bluetoolthchatservice object, which exists in the entire application, and execute the Bluetooth connection establishment and message sending and receiving actions.
3.3 bluetoothchatservice. Java
Public synchronrized void start (); enable the myacceptthread thread. Because the sample program is a chat program of only two people, check whether mconnectthread and mconnnectedthread are running before exiting them.
Public synchrorized void connect (effecthdevice device) cancels ing and connected-related threads and then runs the new mconnectthread.
Public synchronized void connected (effecthsocket socket, effecthdevice device ):
Start a connectedthread to manage the corresponding current connection. Previously, cancel any existing mconnectthread, mconnectedthread, and macceptthread threads, start the new mconnectedthread, and pass in the socket connection that is just accepted. Finally, the UI connection is notified through handler.
Public synchronized void stop ():
Stop all related threads and set the current status to none.
Public void write (byte [] out ):
In the STATE_CONNECTED state, call the write method in mConnectedThread to write bytes.
Private void connectionFailed ():
Handle connection failures, notify the ui, and set the status to STATE_LISTEN.
Private void connectionLost ():
When the connection is lost, it is set to STATE_LISTEN and notifies the ui.
Internal class:
Private class AcceptThread extends Thread:
Create a listening thread and prepare to accept new connections. Call BluetoothServerSocket. accept () in blocking mode (). The cancel method is provided to disable socket.
Private class ConnectThread extends Thread:
This is a defined connection thread that is used to send a request and process for connecting the Bluetooth of the other party. In the constructor, mongothdevice. createRfcommSocketToServiceRecord () is used to generate the initthsocket from the device to be connected. connect to the device in the run method, and call the connethchatsevice connected () method. Define cancel () to close the socket when the thread is closed.
Private class ConnectedThread extends Thread:
This is the thread that is always running after the two sides connect to IOT platform through Bluetooth. Set the input and output streams in the constructor. In the run method, use the inputstream. Read () method in blocking mode to read the input stream cyclically, and then post it to the UI thread to update the chat message. Write () is also provided to write the chat message to the output stream and transmit it to the other party. After successful transmission, the chat message is written back to the UI thread. Finally, cancel () closes the connected socket.
3.4. devicelistactivity. Java
This class contains the UI and operation activity categories. This class is used to obtain the list of paired devices of the default bluetooth device and the list of unpaired new devices found. Then, you can click to send a connection request to the device.
In addition to RFCOMM communication, there are also Bluetooth SDP, Gap, and headset device connections on Android. This article is not covered yet and will be further improved with the Bluetooth related APIs in the new version.