use of Bluetooth module in Android
1. Response Permissions using Bluetooth
<uses-permission android:name= "Android.permission.BLUETOOTH"/> <uses-permission android:name= " Android.permission.BLUETOOTH_ADMIN "/>
2. Configure the native Bluetooth module
Here first to understand the Bluetooth operation a core class Bluetoothadapter
Bluetoothadapter adapter =Bluetoothadapter.getdefaultadapter (); //Open the system's Bluetooth settings panel directlyIntent Intent =NewIntent (bluetoothadapter.action_request_enable); Startactivityforresult (Intent,0x1); //turn on Bluetooth directlyadapter.enable (); //Turn off Bluetoothadapter.disable (); //turn on the Bluetooth Discovery feature on this computer (the default is 120 seconds, you can extend the time up to 300 seconds)Intent discoveryintent =NewIntent (bluetoothadapter.action_request_discoverable); Discoverableintent.putextra (Bluetoothadapter.extra_discoverable_duration,300);//Set duration (up to 300 seconds)
3. Search for Bluetooth devices
Use Bluetoothadapter's StartDiscovery () method to search for Bluetooth devices
The StartDiscovery () method is an asynchronous method that is returned immediately after the call. This method searches for other Bluetooth devices, which lasts for 12 seconds. After the method call, the search process is actually done in a system service, so you can call the Canceldiscovery () method to stop the search (which can be called when the discovery request is not executed).
After requesting discovery, the system starts searching for the Bluetooth device, during which the system sends the following three broadcasts:
Action_discovery_start: Start Search
Action_discovery_finished: End of search
Action_found: Find the device, this intent contains two EXTRA fields:extra_device and Extra_class, respectively, including Bluetoodevice and Bluetoothclass.
We can register the corresponding broadcastreceiver to receive the broadcast of the response, in order to implement some functions
//Create a broadcastreceiver that receives Action_found broadcastsPrivate FinalBroadcastreceiver Mreceiver =NewBroadcastreceiver () { Public voidOnReceive (Context context, Intent Intent) {String action=intent.getaction (); //Discover Devices if(BluetoothDevice.ACTION_FOUND.equals (ACTION)) {//getting device objects from intentBluetoothdevice device =Intent.getparcelableextra (Bluetoothdevice.extra_device); //Place the device name and address into array adapter to display in the ListViewMarrayadapter.add (Device.getname () + "\ n" +device.getaddress ()); } } }; //Register BroadcastreceiverIntentfilter filter =NewIntentfilter (Bluetoothdevice.action_found); Registerreceiver (mreceiver, filter); //don't forget to unbind it later
4. Bluetooth Socket Communication
If you intend to recommend a connection between the two Bluetooth devices, you must implement the server-side and client mechanisms. When two devices have a connected bluetoothsocket under the same Rfcomm channel, the two devices can be said to have established a connection.
The way that server devices get Bluetoothsocket with client devices is different. The server device is obtained by accepted a incoming connection, while the client device is obtained by opening a RFCOMM channel to the server.
Server-side implementation
By calling Bluetoothadapter's Listenusingrfcommwithservicerecord (String, UUID) method to get the Bluetoothserversocket (UUID used for pairing between client and server side)
Call Bluetoothserversocket's Accept () method to listen for the connection request, and if the request is received, return an Bluetoothsocket instance (this method is the block method, which should be placed in a new thread)
If you do not want to accept other connections, call Bluetoothserversocket's Close () method to release the resource ( after calling the method, the previously obtained Bluetoothsocket instance does not have close. However, since Rfcomm is allowed to have only one connection in one channel at a time, it is generally close after the accept a connection Bluetoothserversocket)
Private classAcceptthreadextendsThread {Private FinalBluetoothserversocket Mmserversocket; PublicAcceptthread () {//Use a temporary object, which is later assigned to Mmserversocket,//because Mmserversocket is finalBluetoothserversocket tmp =NULL; Try { //My_uuid is the app's UUID string, also used by the client codeTMP =Mbluetoothadapter.listenusingrfcommwithservicerecord (NAME, My_uuid); } Catch(IOException e) {} Mmserversocket=tmp; } Public voidrun () {Bluetoothsocket 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; } } } /**Would cancel the listening socket, and cause the thread to finish*/ Public voidCancel () {Try{mmserversocket.close (); } Catch(IOException e) {}}}
Implementation of the Client
Get server-side bluetoothservice by searching
Call Bluetoothservice's Listenusingrfcommwithservicerecord (String, uuid) method to get the Bluetoothsocket (the UUID should be the same as the server-side UUID)
Call the Connect () method of Bluetoothsocket (which is the Block method), and if the UUID matches the server-side UUID and the connection is accepted by the server, the Connect () method returns
Note: Before calling the Connect () method, you should make sure that no search devices are currently present, otherwise the connection becomes very slow and easy to fail
Private classConnectthreadextendsThread {Private FinalBluetoothsocket Mmsocket; Private FinalBluetoothdevice Mmdevice; PublicConnectthread (Bluetoothdevice device) {//Use a temporary object, which is later assigned to Mmsocket,//because Mmsocket is finalBluetoothsocket tmp =NULL; Mmdevice=device; //Get a bluetoothsocket to connect with the given Bluetoothdevice Try { //My_uuid is the app's UUID string, also used by the server codeTMP =Device.createrfcommsockettoservicerecord (MY_UUID); } Catch(IOException e) {} Mmsocket=tmp; } Public voidrun () {//Cancel Discovery because it'll slow down the connectionMbluetoothadapter.canceldiscovery (); Try { //Connect the device through the socket. this would block//until it succeeds or throws an exceptionMmsocket.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); } /**Would cancel an in-progress connection, and close the socket*/ Public voidCancel () {Try{mmsocket.close (); } Catch(IOException e) {}}}
Connection management (data communication)
InputStream and OutputStream are obtained through Bluetoothsocket's getInputStream () and Getoutputstream () methods respectively
Read and write operations using read (bytes[]) and write (bytes[]) methods
Note: The read (bytes[]) method will always block, knowing that information is read from the stream, while the write (bytes[]) method is not a regular block (for example, the Write method blocks if another device is not in a timely read or the intermediate buffer is full)
Private classConnectedthreadextendsThread {Private FinalBluetoothsocket Mmsocket; Private FinalInputStream Mminstream; Private FinalOutputStream Mmoutstream; PublicConnectedthread (bluetoothsocket socket) {Mmsocket=socket; InputStream Tmpin=NULL; OutputStream Tmpout=NULL; //Get the input and output streams, using temp objects because//member streams is final Try{Tmpin=Socket.getinputstream (); Tmpout=Socket.getoutputstream (); } Catch(IOException e) {} Mminstream=Tmpin; Mmoutstream=tmpout; } Public voidrun () {byte[] buffer =New byte[1024];//Buffer store for the stream intbytes//bytes returned from read ()//Keep listening to the InputStream until an exception occurs while(true) { Try { //Read from the InputStreambytes =mminstream.read (buffer); //Send the obtained bytes to the UI ActivityMhandler.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 voidWritebyte[] bytes) { Try{mmoutstream.write (bytes); } Catch(IOException e) {}}/*Call this from the main Activity to shutdown the connection*/ Public voidCancel () {Try{mmsocket.close (); } Catch(IOException e) {}}}
Excerpt from: http://blog.csdn.net/geekdonie/article/details/7487761
Android bluetooth communication