Analysis on Android Bluetooth Development

Source: Internet
Author: User

A module for data transmission is being developed recently. After reading the relevant documents and reading the Android official documents in detail, this module summarizes the usage of the bluetooth module in Android.

1. Use the response permission of Bluetooth
[Html]
<Uses-permission android: name = "android. permission. BLUETOOTH"/>
<Uses-permission android: name = "android. permission. effecth_admin"/>


2. Configure the local Bluetooth module
First, you need to know how to operate a core class of Bluetooth thadapter.
[Java]
Descrithadapter adapter = descrithadapter. getdefaadapter adapter ();
// Directly open the system's bluetooth settings panel
Intent intent = new Intent (effecthadapter. ACTION_REQUEST_ENABLE );
StartActivityForResult (intent, 0x1 );
// Enable Bluetooth directly
Adapter. enable ();
// Disable Bluetooth
Adapter. disable ();
// Enable the local Bluetooth detection function (120 seconds by default, and the maximum time can be extended to 300 seconds)
DiscoverableIntent. putExtra (effecthadapter. EXTRA_DISCOVERABLE_DURATION, 300); // sets the duration (up to 300 seconds) Intent discoveryIntent = new Intent (effecthadapter. ACTION_REQUEST_DISCOVERABLE );

3. Search for Bluetooth devices
Use startDiscovery () method of descrithadapter to search for Bluetooth devices
The startDiscovery () method is an asynchronous method that is returned immediately after being called. This method searches for other Bluetooth devices for 12 seconds. After this method is called, the search process is actually performed in a System Service, so you can call the cancelDiscovery () method to stop the search (this method can be called when the discovery request is not executed ).
After a request for Discovery, the system starts searching for the bluetooth device. During this process, the system sends the following three broadcasts:
ACTION_DISCOVERY_START: Start search
ACTION_DISCOVERY_FINISHED: search ends
ACTION_FOUND: locate the device. This Intent contains two extra fields: EXTRA_DEVICE and EXTRA_CLASS, which respectively include the external device and the external thclass.
We can register the corresponding BroadcastReceiver to receive the response broadcast, so as to implement some functions.
[Java]
// Create a BroadcastReceiver that receives the ACTION_FOUND Broadcast
Private final BroadcastReceiver mReceiver = new BroadcastReceiver (){
Public void onReceive (Context context, Intent intent ){
String action = intent. getAction ();
// Device discovery
If (descrithdevice. ACTION_FOUND.equals (action )){
// Get the device object from Intent
Effecthdevice device = intent. getParcelableExtra (effecthdevice. EXTRA_DEVICE );
// Put the device name and address in array adapter for display in ListView
MArrayAdapter. add (device. getName () + "\ n" + device. getAddress ());
}
}
};
// Register BroadcastReceiver
IntentFilter filter = new IntentFilter (effecthdevice. ACTION_FOUND );
RegisterReceiver (mReceiver, filter); // do not forget to unbind it.


4. Bluetooth Socket communication
If you plan to recommend a connection between two bluetooth devices, you must implement a mechanism between the server and the client. When the two devices have a dedicated thsocket under the same RFCOMM channel, the two devices can be said to have established a connection.
The way for the server and client devices to obtain the thsocket is different. The server device is obtained through an incoming connection, while the client device is obtained by opening an RFCOMM channel to the server.

Server implementation
Call the listenUsingRfcommWithServiceRecord (String, UUID) method of javasthadapter to obtain javasthserversocket (UUID is used for pairing between the client and the server)
Call the BluetoothServerSocket's accept () method to listen for connection requests. If the request is received, a BluetoothSocket instance is returned (this method is a block method and should be placed in a new thread)
If you do not want other connections in accept, call the close () method of ipvthserversocket to release the resource (after this method is called, the previously obtained mongothsocket instance is not closed. However, since RFCOMM can only have one connection in one channel at a time, usually the BluetoothServerSocket is closed after an accept connection)
[Java]
Private class AcceptThread extends Thread {
Private final rabbitthserversocket mmServerSocket;
 
Public AcceptThread (){
// Use a temporary object that is later assigned to mmServerSocket,
// Because mmServerSocket is final
Descrithserversocket tmp = null;
Try {
// MY_UUID is the app's UUID string, also used by the client code
Tmp = mblustmthadapter. listenUsingRfcommWithServiceRecord (NAME, MY_UUID );
} Catch (IOException e ){}
MmServerSocket = tmp;
}
 
Public void run (){
Descrithsocket socket = null;
// Keep listening until exception occurs or a socket is returned
While (true ){
Try {
Socket = mmServerSocket. accept ();
} Catch (IOException e ){
Break;
}
// If a connection was accepted
If (socket! = Null ){
// Do work to manage the connection (in a separate thread)
ManageConnectedSocket (socket );
MmServerSocket. close ();
Break;
}
}
}
 
/** Will cancel the listening socket, and cause the thread to finish */
Public void cancel (){
Try {
MmServerSocket. close ();
} Catch (IOException e ){}
}
}


Client implementation: www.2cto.com
Search for the server-side initthservice
Call the listenUsingRfcommWithServiceRecord (String, UUID) method of ipvthservice to obtain the parameter thsocket (the UUID should be the same as the UUID on the server)
Call the connect () method of ipvthsocket (this method is the block method). If the UUID matches the UUID on the server and the connection is accept on the server, the connect () method returns
Note: Before calling the connect () method, make sure that no device is currently searched. Otherwise, the connection will become very slow and easy to fail.
[Java]
Private class ConnectThread extends Thread {
Private final ipvthsocket mmSocket;
Private final effecthdevice mmDevice;
 
Public ConnectThread (effecthdevice device ){
// Use a temporary object that is later assigned to mmSocket,
// Because mmSocket is final
Optional thsocket tmp = null;
MmDevice = device;
 
// Get a pair thsocket to connect with the given pair thdevice
Try {
// MY_UUID is the app's UUID string, also used by the server code
Tmp = device. createRfcommSocketToServiceRecord (MY_UUID );
} Catch (IOException e ){}
MmSocket = tmp;
}
 
Public void run (){
// Cancel discovery because it will slow down the connection
Mblustmthadapter. cancelDiscovery ();
 
Try {
// Connect the device through the socket. This will block
// Until it succeeds or throws an exception
MmSocket. 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 );
}
 
/** Will cancel an in-progress connection, and close the socket */
Public void cancel (){
Try {
MmSocket. close ();
} Catch (IOException e ){}
}
}


Connection Management (Data Communication)
Use getInputStream () and getOutputStream () Methods of ipvthsocket to obtain InputStream and OutputStream respectively.
Use the read (bytes []) and write (bytes []) Methods to perform read and write operations respectively.
Note: The read (bytes []) method always blocks and knows the Information read from the stream, while write (bytes []) the method is not a regular block (for example, if another device does not read the data in time or the intermediate buffer is full, the write method blocks the data)
[Java]
Private class ConnectedThread extends Thread {
Private final ipvthsocket mmSocket;
Private final InputStream mmInStream;
Private final OutputStream mmOutStream;
 
Public ConnectedThread (Fig socket ){
MmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
 
// Get the input and output streams, using temp objects because
// Member streams are final
Try {
TmpIn = socket. getInputStream ();
TmpOut = socket. getOutputStream ();
} Catch (IOException e ){}
 
MmInStream = tmpIn;
MmOutStream = tmpOut;
}
 
Public void run (){
Byte [] buffer = new byte [1024]; // buffer store for the stream
Int bytes; // bytes returned from read ()
 
// Keep listening to the InputStream until an exception occurs
While (true ){
Try {
// Read from the InputStream
Bytes = mmInStream. read (buffer );
// Send the obtained bytes to the UI Activity
MHandler. obtainMessage (MESSAGE_READ, bytes,-1, buffer)
. SendToTarget ();
} Catch (IOException e ){
Break;
}
}
}
 
/* Call this from the main Activity to send data to the remote device */
Public void write (byte [] bytes ){
Try {
MmOutStream. write (bytes );
} Catch (IOException e ){}
}
 
/* Call this from the main Activity to shutdown the connection */
Public void cancel (){
Try {
MmSocket. close ();
} Catch (IOException e ){}
}
}


From Crazy Programmer

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.