Android Bluetooth Serial Communication
The Android bluetooth module communicates with the single-chip bluetooth module. The simple idea is that the mobile phone sends control commands to the single-chip microcomputer through Bluetooth for simple control applications. Single Chip Microcomputer bluetooth module connection and program temporarily skipped, this article mainly describes the Android mobile phone Bluetooth client encountered that point of breakthrough. Enter the subject:
Connect to the bluetooth device-Bluetooth client:
Android phones generally use the client roleActiveConnect to the SPP protocol device (connect to the digital sensor of the bluetooth module). The client connection process is as follows:
1. Use registerReceiver to register BroadcastReceiver to obtain Bluetooth status, search for devices, and other messages;
PrivateBroadcastReceiversearchDevices =NewBroadcastReceiver (){
PublicvoidOnReceive (Context context, Intent intent ){
String action = intent. getAction ();
Bundle B = intent. getExtras ();
Object [] lstName = B. keySet (). toArray ();
// Display all received messages and their details
For(IntI = 0; I <lstName. length; I ++ ){
String keyName = lstName [I]. toString ();
Log.E(KeyName, String.ValueOf(B. get (keyName )));
}
// Retrieve the MAC address of the device when searching for the device
If(Effecthdevice.ACTION_FOUND. Equals (action )){
Descrithdevice device = intent
. GetParcelableExtra (effecthdevice.EXTRA_DEVICE);
String str = device. getName () + "|" + device. getAddress ();
If(LstDevices. indexOf (str) =-1) // prevent repeated addition
LstDevices. add (str); // obtain the device name andMacAddress
AdtDevices. notifyDataSetChanged ();
}
}
};
2. Search Using BlueAdatper:
BtAdapt. startDiscovery ();
3. Obtain the bluetooth device information (such as name, MAC, and image service) obtained by searching in onReceive () of BroadcastReceiver );
4. Create a thdevice object through the MAC address of the device;
5. The initthdevice generates the initthsocket and prepares the SOCKET to read and write the device;
6. Use createRfcommSocketToServ of ipvthsocketThe iceRecord () method is used to select the Protocol/service to connect. Is SPP (UUID: 20171101-0000-1000-8000-00805f9b34fb );
Try{
BtSocket= BtDev. createRfcommSocketToServIceRecord (uuid );
}Catch(IOException e ){
//TODOAuto-generated catch block
Log.E(TAG, "Low: Connection failed.", e );
}
Connect after successful:
Try{
BtSocket. Connect ();
Log.E(TAG, "BT connection established, data transfer linkopen .");
MangeConnectedSocket (btSocket); // User-Defined Function for Bluetooth Communication
}Catch(IOException e ){
Log.E(TAG, "Connection failed.", e );
SetTitle ("connection failed ..");
}
7. After Connect (the system will automatically prompt if no pairing is available), use
GetInputStream () and getOutputStream () of ipvthsocket to read and write Bluetooth devices.
Read/write can be implemented in an independent thread ~ Note: The serial port buffer must be read cyclically at the time of reading. Write is not required.
After following the above seven steps, you will find out how difficult the Android bluetooth module is.
Problem:
In step 1, an exception occurs in Connection refused execution.
What should I do if the execution fails?
As a result, I searched for the strategy on the Internet while debugging, and finally found some practices for foreigners on Google. It seems feasible to try again. That is
The establishment method of btSocket is replaced by another method. Port 1 is used here.
Method m;
Try{
M = btDev. getClass (). getMethod ("createRfcommSocket ",NewClass [] {Int.Class});
BtSocket= (Effecthsocket) m. invoke (btDev, Integer.ValueOf(1 ));
}Catch(SecurityException e1 ){
//TODOAuto-generated catch block
E1.printStackTrace ();
}Catch(NoSuchMethodException e1 ){
//TODOAuto-generated catch block
E1.printStackTrace ();
}Catch(IllegalArgumentExceptionE ){
//TODOAuto-generated catch block
E. printStackTrace ();
}Catch(IllegalAccessException e ){
//TODOAuto-generated catch block
E. printStackTrace ();
}Catch(InvocationtargeteffectioN e ){
//TODOAuto-generated catch block
E.PrintStackTrace();
}
So far, this problem seems to have been solved, and the program continues to run.
But remember the previous exceptions here ~ People may not always be abnormal.
The next task is to enable the mobile phone to communicate with the single-chip bluetooth module, send data, and display it through the computer serial port debugging assistant. The specific implementation is implemented in the mangeConnectedSocket (btSocket) method by starting another Activity. Not important. Skipped.
Till now, we only use the mobile phone Bluetooth module as a client. When will it be used on the server? In fact, the single-chip bluetooth module acts as the server (in the listening status, connected by the mobile phone Bluetooth) for communication between the mobile phone Bluetooth module and the single-chip bluetooth module ). In order to better understand Android Bluetooth communication, we will use two mobile phones for Bluetooth communication. Simply put, it is to make a "mobile phone Bluetooth Buckle ",
In the beginning, I tried to burn the previous program to two mobile phones at the same time, and found that only one mobile phone could establish a socket connection (the one that actively connects ), the other one has not responded yet. The reason is very simple. The program on the server has not been written yet!
So, start the server program: Open up a new thread implementation
Connect to the bluetooth device-Bluetooth server:
ClassAcceptThreadExtendsThread {
PrivatefinalBluetoothServerSocketserverSocket;
PublicAcceptThread (){
// Use a temporary object that is later assignedto mmServerSocket,
// Because mmServerSocket isfinal
Descrithserversocket tmp =Null;
Try{
//Tmp= BtAdapt. listenUsingRfcommWithSerViceRecord ("mydomainthapp ",Uuid);
Log.E(TAG, "++ Implements thserversocketestablished! ++ ");
Method listenMethod = BtAdapt. getClass (). getMethod ("listenUsingRfcommOn ",
New Class [] {Int.Class});
Tmp = (Fig socket) listenMethod. invoke (btAdapt, Integer.ValueOf(1 ));
}Catch(SecurityException e ){
//TODOAuto-generated catch block
E. printStackTrace ();
}Catch(IllegalArgumentExceptionE ){
//TODOAuto-generated catch block
E. printStackTrace ();
}Catch(NoSuchMethodException e ){
//TODOAuto-generated catch block
E. printStackTrace ();
}Catch(IllegalAccessException e ){
//TODOAuto-generated catch block
E. printStackTrace ();
}Catch(InvocationtargeteffectioN e ){
//TODOAuto-generated catch block
E. printStackTrace ();
}
ServerSocket = tmp;
}
PublicvoidRun (){
// Keep listening until exception occurs or asocket is returned
// MState! = STATE_CONNECTED
While(True) {// This is a loop listener, or you can set the mState to determine
Try{
Socket= ServerSocket. accept ();
Log.E(TAG, "++ Javasthsocket established! DataLinkopen. ++ ");
}Catch(IOException e ){
Break;
}
// If a connection was accepted
If(Socket! =Null){
// Do work to manage the connection (in a separatethread)
ManageConnectedSocket ();
Try{
ServerSocket. close ();
}Catch(IOException e ){
//TODOAuto-generated catch block
E. printStackTrace ();
}
Break;
}
}
}
PublicvoidCancel (){
Try{
ServerSocket. close ();
}Catch(IOException e ){}
}
}
Installation test:After the two mobile phones are installed and the same program is opened, they can be searched and connected via Bluetooth. After testing, they can be connected successfully and both enter the "chat interface ".
Note: At this time, the previous exception is retrieved again, and the method for establishing the socket connection is changed
BtSocket= BtDev. createRfcommSocketToServIceRecord (uuid); // Client
Corresponding server program:
Tmp= BtAdapt. listenUsingRfcommWithSerViceRecord ("mydomainthapp ",Uuid); // Server
In this way, the installation test is continued, and the previous bug disappears after running on two mobile phones ~ Two mobile phones both enter the chat interface.
Magic ~
Bug:
One mobile phone can only start one active connection as a client. When the chat interface is exited and the main interface is returned (the AcceptThread of the server is still running ), when you connect to another mobile phone again, an exception Connection refused is reported. That is to say, an error occurs when the client's bluetooth socket is connected twice ~ (Note that the Bluetooth Connection Program of my client is not put into an independent thread, but in a button listening event)
I 've been tossing for a long time, but I didn't find any reason. It seems that I had to restart the program once I quit again. Which of the following experts knows why!
If you need code, download the code