Android has packaged a number of calling interfaces for communication between Bluetooth devices, making it easy to implement the Bluetooth communication capabilities of Android. The UUID allows two devices to be connected directly to each other.
Specific steps:
1. Get Bluetoothadapter instances, register a broadcastreceiver monitor for status changes during Bluetooth scanning
Mbluetoothadapter = Bluetoothadapter.getdefaultadapter ();
Intentfilter filter = new Intentfilter (bluetoothdevice.action_found); Registerreceiver (mreceiver, filter);
Private final Broadcastreceiver mreceiver = new Broadcastreceiver () {@Override public void onreceive (Contex T context, Intent Intent) {String action = intent.getaction (); When discovery finds a device if (BluetoothDevice.ACTION_FOUND.equals (ACTION)) { Get the Bluetoothdevice object from the Intent//by Extra_device additional domain to get a bluetoothdevice device Blu Etoothdevice device = Intent.getparcelableextra (Bluetoothdevice.extra_device); If it's already paired, skip it, because it's been listed already//if this device is never paired, add to List if (device.getbondstate ()! = bluetoothdevice.bond_bonded) {list.add (New Chatmessage (DE Vice.getname () + "\ n" + device.getaddress (), false)); Clientadapter.notifydatasetchanged (); Mlistview.setselection (List.size ()-1); }//When Discovery is finished, change the Activity title} else if (Bluetoothadapter.action_discovery_fini Shed.equals (Action)) {setprogressbarindeterminatevisibility (false); if (mlistview.getcount () = = 0) {list.add (New Chatmessage ("No Bluetooth device found", false)); Clientadapter.notifydatasetchanged (); Mlistview.setselection (List.size ()-1); } } } };
2. Turn on Bluetooth (enable), and set the visibility of Bluetooth (can be scanned by other devices, the client is unsolicited request, not set, the server must be set visible).
if (mbluetoothadapter! = null) {if (!mbluetoothadapter.isenabled ()) {//sends open Bluetooth intent, the system pops up a prompt dialog box Intent enableintent = new Intent (bluetoothadapter.action_request_enable); Startactivityforresult (Enableintent, result_first_user); Set the visibility of Bluetooth, maximum 3,600 seconds, default 120 seconds, 0 means always visible (as client, visibility can not be set, server must be set) Intent displayintent = new Intent ( bluetoothadapter.action_request_discoverable); Displayintent.putextra (bluetoothadapter.extra_discoverable_duration, 0); StartActivity (displayintent); Open Bluetooth mbluetoothadapter.enable directly ();}}
3. Scanning, StartDiscovery () method is a performance-intensive operation, before scanning can use Getbondeddevices () to obtain a paired device (can be directly connected), to avoid unnecessary consumption.
private void Scandevice () {//TODO auto-generated method Stub if (Mbluetoothadapter.isdiscovering ()) { Mbluetoothadapter.canceldiscovery ();} else {//before each scan, determine if there is a paired device set<bluetoothdevice> paireddevices = mbluetoothadapter.getbondeddevices ( ); if (paireddevices.size () > 0) {for (Bluetoothdevice device:paireddevices) { list.add (new Chatmessage ( Device.getname () + "\ n" + device.getaddress (), True));} } else { List.add (new Chatmessage ("No devices has been paired", true)); Clientadapter.notifydatasetchanged (); Mlistview.setselection (List.size ()-1); } /* Start Search * /Mbluetoothadapter.startdiscovery ();}}
4. Send the connection request via the MAC address, before which the scan must be stopped using the Canceldiscovery () method.
Mbluetoothadapter.canceldiscovery ();//Try connecting a device with a MAC address bluetoothdevice device = Mbluetoothadapter.getremotedevice ( bluetoothmsg.bluetoothaddress);
5. Create a connection between two devices via the UUID.
Client: Unsolicited request
Bluetoothsocket socket = Device.createrfcommsockettoservicerecord (uuid.fromstring (" 00001101-0000-1000-8000-00805F9B34FB ")); Connect the server through the socket, which is a blocking process until the connection is established or the connection fails socket.connect ();
Service side: Accept a request
Bluetoothserversocket Mserversocket = Mbluetoothadapter.listenusingrfcommwithservicerecord (PROTOCOL_SCHEME_RFCOMM , Uuid.fromstring ("00001101-0000-1000-8000-00805F9B34FB")); /* Accept the client's connection request * ///This is a blocking process until a connection is established or the connection fails //A Bluetoothsocket object is obtained by Bluetoothserversocket to manage this connection Bluetoothsocket socket = mserversocket.accept ();
6. Through the Inputstream/outputstream read and write data stream, has achieved the communication purpose.
OutputStream OS = Socket.getoutputstream (); Os.write (Msg.getbytes ());
InputStream is = null; try {is = Socket.getinputstream (); } catch (IOException e) { //TODO auto-generated catch block e.prints Tacktrace (); }
7. Close all threads and sockets, and turn off the Bluetooth device (disable).
if (mclientthread! = null) { mclientthread.interrupt (); Mclientthread = null;} if (mreadthread! = null) {mreadthread.interrupt (); mreadthread = null;} try {if (socket! = NULL) {socket.close (); socket = null;}} catch (IOException e) {//Todo:handle exception}
if (mbluetoothadapter! = null) {mbluetoothadapter.canceldiscovery ();//Turn off Bluetooth mbluetoothadapter.disable ();} Unregisterreceiver (Mreceiver);
The main step is these, in order to better understand, I have the server side and the client's code to write two programs,: http://download.csdn.net/detail/visionliao/8417235
Android Bluetooth communication