Learning Route
1 Bluetooth permissions
<android:name= "Android.permission.BLUETOOTH"/>< android:name= "Android.permission.BLUETOOTH_ADMIN"/>< android:name= "Android.permission.ACCESS_COARSE_LOCATION"/>//Android 6.0 version requires location permissions
2 Turn on Bluetooth
public void OnOpen (View v) { bluetoothadapter = Bluetoothadapter.getdefaultadapter ();//Get the Bluetooth adapter if (! Bluetoothadapter.isenabled ()) { //If Bluetooth is off, open bluetoothadapter.enable (); ShowMessage ("Open bluetooth"); } else { ShowMessage ("Bluetooth is already open"); } }
3 scan around Bluetooth (get paired Bluetooth)
Scanning the surrounding Bluetooth needs to define a broadcast receiver
PrivateBroadcastreceiver mreceiver=NewBroadcastreceiver () {@Override Public voidOnReceive (Context context, Intent Intent) {String action=intent.getaction (); LOG.I ("Boye", action); if(Action.equals (Bluetoothdevice.action_found)) {Bluetoothdevice device=Intent.getparcelableextra (Bluetoothdevice.extra_device); Get the device you are currently scanning toif(Device.getbondstate () ==bluetoothdevice.bond_bonded) {//Show paired DevicesTextview.append ("\ n" +device.getname () + "==>" +device.getaddress () + "\ n"); Toast.maketext (Context,"Found paired device:" +device.getname (), Toast.length_long). Show (); } Else if(Device.getbondstate ()! =bluetoothdevice.bond_bonded) {Textview3.append ("\ n" +device.getname () + "==>" +device.getaddress () + "\ n"); Toast.maketext (Context,"Found an unpaired device:" +device.getname (), Toast.length_long). Show (); } } Else if(Action.equals (bluetoothadapter.action_discovery_finished)) {Textview2.settext ("Search Complete ..."); } } };
Broadcast filters
Intentfilter filter=New intentfilter (bluetoothdevice.action_found); Filter out found Registerreceiver (mreceiver,filter); Registered broadcast Intentfilter Filter2=new intentfilter (bluetoothadapter.action_discovery_finished); Filter out the scanning end registerreceiver (mreceiver,filter2); //Registered broadcast
4 Bluetooth pairing
public void Createbond (Bluetoothdevice Btdev, Handler Handler) { if (Btdev.getbondstate () == Bluetoothdevice.bond_none) { // If this device cancels pairing, try pairing if (Build.VERSION.SDK_INT >= Build.version_codes. KITKAT) {//Android version greater than or equal to 4.3 btdev.createbond (); }} else if (btdev.getbondstate () = = bluetoothdevice.bond_bonded) { // If this device is already paired, try connecting to Connect (Btdev, handler); } }
5 Bluetooth connection
Private voidConnect (bluetoothdevice Btdev, Handler Handler) {Try { //connect through the UUID that is negotiated with the serverMbluetoothsocket =Btdev.createrfcommsockettoservicerecord (BLTCONTANT.SPP_UUID); if(Mbluetoothsocket! =NULL) //There is only one Bluetooth in the global, so we can save this socket object in AppliactionBltappliaction.bluetoothsocket =Mbluetoothsocket; LOG.I ("BlueTooth", "Start connection ..."); //called before it is established if(Getmbluetoothadapter (). isdiscovering ())//Stop SearchGetmbluetoothadapter (). Canceldiscovery (); //if the current socket is in a non-connected state, the connection is called if(!Getmbluetoothsocket (). isconnected ()) { //you should make sure that the device does not perform the search device operation when you call Connect (). //If the search device is also at the same time, the connection rate will be significantly reduced and the connection will fail to a large extent. getmbluetoothsocket (). connect (); } log.i ("BlueTooth", "Already connected"); if(Handler = =NULL)return; //Result CallbackMessage message =NewMessage (); Message.what= 4; Message.obj=Btdev; Handler.sendmessage (message); } Catch(Exception e) {log.i ("BlueTooth", "... Connection Failed "); Try{getmbluetoothsocket (). Close (); } Catch(IOException E1) {e1.printstacktrace (); } e.printstacktrace (); } }
6 Bluetooth communication
(1) Send a message
Public Static voidsendMessage (String message) {if(Bltappliaction.bluetoothsocket = =NULL|| Textutils.isempty (message))return; Try { //message + = "\ n";OutputStream OutputStream =BltAppliaction.bluetoothSocket.getOutputStream (); Outputstream.write (Message.getbytes ("Utf-8")); Outputstream.flush (); } Catch(IOException e) {e.printstacktrace (); } }}
(2) Receiving messages
Public Static voidreceiveMessage (Handler Handler) {if(Bltappliaction.bluetoothsocket = =NULL|| Handler = =NULL)return; Try{InputStream InputStream=BltAppliaction.bluetoothSocket.getInputStream (); byte[] buffer =New byte[200]; Inputstream.read (buffer); LOG.I ("Information received by Boye",NewString (buffer)); Message Message=NewMessage (); Message.obj=NewString (buffer); Message.what= 1; Handler.sendmessage (message); } Catch(IOException e) {e.printstacktrace (); } }
Android Bluetooth Learning