Android Adapter 6.0 Bluetooth communication implementation process _android

Source: Internet
Author: User
Tags uuid

Prior description:
Andoran teeth need to locate the right to apply, in the Android 6.0 users need to manually confirm the right to use, you can query the data to achieve, if it is troublesome, you can use the Third-party Bmob Integrated tool class implementation, detailed can see Http://blog.csdn.net/qq_ 30379689/article/details/52223244

Bluetooth connection process:
1, query whether the user to open Bluetooth.
2, search the vicinity of available Bluetooth.
3, Bluetooth pairing.
4, the Bluetooth connection.
5. Get input stream and output stream.
6, send the message.

To bask in the beauty of my own drawings:


Experiment Effect Chart:

To achieve the required permissions: since Android version 4.x above the use of Bluetooth, you need to turn on location permissions to search the nearby Bluetooth device

<uses-permission android:name= "Android.permission.BLUETOOTH"/> 
<uses-permission android:name= " Android.permission.BLUETOOTH_ADMIN "/> 
 
<uses-permission android:name=" android.permission.ACCESS_FINE_ LOCATION "/> 
<uses-permission android:name=" Android.permission.ACCESS_COARSE_LOCATION "/>" 

Service side

Realize the idea:
1, get the local Bluetooth equipment.
2, the communication between Bluetooth requires a unique identification UUID to match the correct device, using the UUID to obtain Bluetooth communication socket.
3, open the thread to get the data

public class Mainactivity extends Appcompatactivity implements View.onclicklistener {Bluetoothsocket btsocket; 
 Bluetoothadapter Btadapter; 
 Button Bt_start; 
 TextView tv_msg; 
 
 StringBuilder SB; 
 @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
 Setcontentview (R.layout.activity_main); 
 Bt_start = (Button) Findviewbyid (R.id.bt_start); 
 Tv_msg = (TextView) Findviewbyid (r.id.tv_msg); 
 Bt_start.setonclicklistener (this); 
 SB = new StringBuilder (); 
 Get the local bluetooth device Btadapter = Bluetoothadapter.getdefaultadapter (); 
 /** * UI Text Output * * @param msg/public void Show (String msg) {sb.append (msg + "\ n"); 
 Runonuithread (New Runnable () {@Override public void run () {Tv_msg.settext (sb.tostring ()); 
 } 
 }); 
 @Override public void OnClick (View v) {//open server Serverthread startserverthread = new Serverthread (); 
 Startserverthread.start (); /** * Open Server/private class Serverthread EXtends Thread {public void run () {try {bluetoothserversocket mserversocket = Btadapter.listenusingrfcommwithservi 
 Cerecord ("BTSPP", Uuid.fromstring ("00001101-0000-1000-8000-00805F9B34FB")); 
 
 Show ("Service side: Waiting for Connection"); 
 Btsocket = Mserversocket.accept (); 
 
 Show ("Service side: Connection successful"); 
 Readthread mreadthread = new Readthread (); 
 Mreadthread.start (); 
 Show ("Server: Start receiving data"); 
 catch (IOException e) {e.printstacktrace (); }}/** * Read data/Private class Readthread extends Thread {public void run () {byte[] buffer = new by 
 TE[1024]; 
 int bytes; 
 InputStream mminstream = null; 
 try {mminstream = Btsocket.getinputstream (); 
 Show ("Server: Get input stream"); 
 catch (IOException E1) {e1.printstacktrace (); 
  } while (true) {try {if (bytes = mminstream.read (buffer) > 0) {byte[] Buf_data = new Byte[bytes]; 
  for (int i = 0; i < bytes i++) {Buf_data[i] = Buffer[i]; 
  string s = new string (buf_data); 
  Show ("Server: Read the data ~ ~" + s); catch (IOException e) {try {mminstream.close (); 
  catch (IOException E1) {e1.printstacktrace (); 
 } break; 

 } 
 } 
 } 
 } 
 
}

Client

Realize the idea:
1, check whether to open Bluetooth.
2, register a series of Bluetooth broadcast.
3, by Yulan each stage will send a broadcast, according to the broadcast to achieve the corresponding method.
4, Bluetooth pairing-> bluetooth connection-> Send message (UUID must be the same)

public class Mainactivity extends Appcompatactivity implements View.onclicklistener {private TextView tv_msg; 
 Private Button Bt_search, bt_send; 
 Private Bluetoothsocket Btsocket; 
 Private Bluetoothadapter Btadapter; 
 private Bluetoothdevice device; 
 
 Private StringBuilder SB; 
 @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
 
 Setcontentview (R.layout.activity_main); 
 Bt_search = (Button) Findviewbyid (R.id.bt_search); 
 Bt_send = (Button) Findviewbyid (r.id.bt_send); 
 Tv_msg = (TextView) Findviewbyid (r.id.tv_msg); 
 Bt_search.setonclicklistener (this); 
 Bt_send.setonclicklistener (this); 
 
 SB = new StringBuilder (); 
 Show ("Client: Check BT"); 
 CHECKBT (this); 
 Show ("Client: Registered recipient"); 
 Registerbtreceiver (); 
 /** * UI Text Output * * @param msg/public void Show (String msg) {sb.append (msg + "\ n"); 
 Runonuithread (New Runnable () {@Override public void run () {Tv_msg.settext (sb.tostring ()); 
 } 
 }); 
 
 }@Override public void OnClick (View v) {switch (V.getid ()) {case R.id.bt_search:show ("Client: Start looking for device"); 
 Btadapter.startdiscovery (); 
 Break 
 Case R.id.bt_send:sendmessage (); 
 Break 
 }/** * Check bluetooth */public void CHECKBT (context context) {Btadapter = Bluetoothadapter.getdefaultadapter (); if (btadapter!= null) {if (!) 
 Btadapter.isenabled ()) {Intent Intent = new Intent (bluetoothadapter.action_request_enable); 
 Set Bluetooth visibility, up to 300 seconds Intent.putextra (Bluetoothadapter.extra_discoverable_duration, 300); 
 Context.startactivity (Intent); 
 } else {System.out.println ("Local device driver exception!"); }/** * Open client/private class Clientthread extends Thread {public void run () {try {///Create a Socket connection: Only require the server to register with the UUID number Btsocket = Device.createrfcommsockettoservicerecord (Uuid.fromstring (" 
 00001101-0000-1000-8000-00805F9B34FB ")); 
 Connect Show ("client: Start connecting ..."); 
 Btsocket.connect (); 
 Show ("Client: Connection successful"); 
 Start accepting data show ("Client: Start acceptance data"); Readthread MreadthrEAD = new Readthread (); 
 Mreadthread.start (); catch (IOException e) {Show ("Client: Connect service-side exception!") 
 Disconnect the connection and try again "); 
 E.printstacktrace (); }}/** * Read data/Private class Readthread extends Thread {public void run () {byte[] buffer = new by 
 TE[1024]; 
 int bytes; 
 InputStream is = null; 
 try {is = Btsocket.getinputstream (); 
 Show ("Client: Get input stream"); 
 catch (IOException E1) {e1.printstacktrace (); 
  } while (true) {try {if (bytes = is.read (buffer) > 0) {byte[] Buf_data = new Byte[bytes]; 
  for (int i = 0; i < bytes i++) {Buf_data[i] = Buffer[i]; 
  string s = new string (buf_data); 
  Show ("Client: Read the data" + s); 
  } catch (IOException e) {try {is.close (); 
  catch (IOException E1) {e1.printstacktrace (); 
 } break;  /** * Send data/public void SendMessage () {if (Btsocket = null) {Toast.maketext (this, no connection) 
 Toast.length_short). Show (); 
 Return try {outputstream OS = Btsocket.getouTputstream (); 
 Os.write ("I Love You dahsid132456@#%¥*". GetBytes ()); 
 Os.flush (); 
 Show ("Client: Send information successfully"); 
 catch (IOException e) {e.printstacktrace (); }/** * Registration broadcast/public void Registerbtreceiver () {//Set Broadcast information filter Intentfilter Intentfilter = new Intentfil 
 ter (); 
 Intentfilter.addaction (Bluetoothdevice.action_found); 
 Intentfilter.addaction (bluetoothadapter.action_discovery_started); 
 Intentfilter.addaction (bluetoothadapter.action_discovery_finished); 
 Intentfilter.addaction (bluetoothadapter.action_state_changed); 
 Intentfilter.addaction (bluetoothdevice.action_bond_state_changed); 
 Registers the broadcast receiver, receives and processes the search result Registerreceiver (btreceive, Intentfilter); 
 /** * Logout broadcast/public void Unregisterbtreceiver () {unregisterreceiver (btreceive); 
 } @Override protected void OnDestroy () {Super.ondestroy (); 
 Unregisterbtreceiver (); /** * Broadcast receiver/private broadcastreceiver btreceive = new Broadcastreceiver () {@Override public void Onrec Eive (COntext context, Intent Intent) {String action = intent.getaction (); if (BluetoothDevice.ACTION_FOUND.equals (ACTION)) {device = Intent.getparcelableextra (Bluetoothdevice.extra_device) 
 ; 
 Show ("Client: Found BT name:" + device.getname ()); 
  If the device found matches the device to be connected, process if (Device.getname (). Equalsignorecase ("Xu")) {Show ("client: Pair Xu Bluetooth:"); 
  The process of searching for Bluetooth devices takes up more resources, and once you find a device that needs to be connected, you need to close the search btadapter.canceldiscovery (); 
  Gets the connection status of the Bluetooth device int connectstate = Device.getbondstate (); 
  Switch (connectstate) {//Not paired case BluetoothDevice.BOND_NONE:show ("Client: Start pairing:"); 
  try {Method Createbondmethod = BluetoothDevice.class.getMethod ("Createbond"); 
  Createbondmethod.invoke (device); 
  catch (Exception e) {e.printstacktrace (); 
  } break; 
  Paired Case BluetoothDevice.BOND_BONDED:try {show ("Client: Start Connection:"); 
  Clientthread clientconnectthread = new Clientthread (); 
  Clientconnectthread.start (); 
  catch (Exception e) {e.printstacktrace (); 
  } break; }} ELSE if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals (ACTION)) {//Get connection status of bluetooth device int connectstate = DEVICE.GETBONDST 
 Ate (); 
  Paired if (connectstate = = bluetoothdevice.bond_bonded) {try {Show ("Client: Start Connection:"); 
  Clientthread clientconnectthread = new Clientthread (); 
  Clientconnectthread.start (); 
  catch (Exception e) {e.printstacktrace (); 
 }} show (action); 
} 
 }; 

 }

Bluetooth Broadcast content:

Action_state_changed when your Bluetooth is turned on or off, send
Action_found when you match to a nearby Bluetooth device, send
action_discovery_started when you start searching for a nearby Bluetooth device, send
Action_discovery_finished when you're done searching for a nearby Bluetooth device, send
action_bond_state_changed when your Bluetooth device matching status changes

SOURCE Download: Http://xiazai.jb51.net/201609/yuanma/Androidrobot (jb51.net). rar

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.