Android development-Bluetooth pairing connection method

Source: Internet
Author: User

The first article of the new year.

Recently, I am working on a small Bluetooth Lock project. There is always a problem when the mobile phone is connected to the single-chip microcomputer, and the connection to the mobile phone is also unstable. I have read many bluetooth documents, I made a summary about the Bluetooth connection.

Android is usually used for Bluetooth serial port connection.

BluetoothSocket tmp = null;// Get a BluetoothSocket for a connection with the// given BluetoothDevicetry {         tmp = device.createRfcommSocketToServiceRecord(MY_UUID);} catch (IOException e) {Log.e(TAG, "create() failed", e);}

Then tmp is assigned to mongothsocket, and then the connect method is called to connect the bluetooth device.

However, the connect Method of ipvthsocket itself reports many exception errors.

The following methods can be used to solve the problem of Bluetooth development:

Method 1. Perform Bluetooth auto-pairing first. The pairing is successful. Obtain the ipvthsocket through UUID, and then execute the connect () method.

Method 2. Obtain the ipvthsocket through UUID, determine whether to pair, and then execute the connnect () method.

 

Private class ConnectThread extends Thread {String macAddress = ""; public ConnectThread (String mac) {macAddress = mac;} public void run () {connecting = true; connected = false; if (mblustmthadapter = null) {mblustmthadapter = descrithadapter. getdefaadapter adapter ();} mbluw.thdevice = mbluw.thadapter. getRemoteDevice (macAddress); mblustmthadapter. cancelDiscovery (); try {socket = mBluetooth Device. createRfcommSocketToServiceRecord (uuid);} catch (IOException e) {// TODO Auto-generated catch block // e. printStackTrace (); Log. e (TAG, "Socket", e);} // adapter. cancelDiscovery (); while (! Connected & connetTime <= 10) {connectDevice () ;}// reset ConnectThread // synchronized (BluetoothService. this) {// ConnectThread = null; //} public void cancel () {try {socket. close (); socket = null;} catch (Exception e) {e. printStackTrace () ;}finally {connecting = false ;}}}

Next, call the connection device method connectDevice ():

Protected void connectDevice () {try {// pair if (mblustmthdevice) before the connection is established. getBondState () = descrithdevice. BOND_NONE) {Method creMethod = effecthdevice. class. getMethod ("createBond"); Log. e ("TAG", "start pairing"); creMethod. invoke (mblustmthdevice);} else {}} catch (Exception e) {// TODO: handle exception // DisplayMessage ("unmatched! "); E. printStackTrace ();} mbluw.thadapter. cancelDiscovery (); try {socket. connect (); // DisplayMessage (" connection successful! "); // ConnetTime ++; connected = true;} catch (IOException e) {// TODO: handle exception // DisplayMessage (" connection failed! "); ConnetTime ++; connected = false; try {socket. close (); socket = null;} catch (IOException e2) {// TODO: handle exception Log. e (TAG, "Cannot close connection when connection failed") ;}} finally {connecting = false ;}}


 

Method 3. Use reflection to obtain the ipvthsocket through the port, and then execute the connect () method.

Private class ConnectThread extends Thread {String macAddress = ""; public ConnectThread (String mac) {macAddress = mac;} public void run () {connecting = true; connected = false; if (mblustmthadapter = null) {mblustmthadapter = descrithadapter. getdefaadapter adapter ();} mbluw.thdevice = mbluw.thadapter. getRemoteDevice (macAddress); mblustmthadapter. cancelDiscovery (); initSocket (); // adapter. c AncelDiscovery (); while (! Connected & connetTime <= 10) {try {socket. connect (); connected = true;} catch (IOException e1) {connetTime ++; connected = false; // close socket try {socket. close (); socket = null;} catch (IOException e2) {// TODO: handle exception Log. e (TAG, "Socket", e2) ;}} finally {connecting = false ;}// connectDevice () ;}// reset ConnectThread // synchronized (BluetoothService. this) {// ConnectThread = null; //} public void cancel () {try {socket. close (); socket = null;} catch (Exception e) {e. printStackTrace () ;}finally {connecting = false ;}}}

The next step is to initialize and obtain the thsocket method.

/*** Get maid/private void initSocket () {fig temp = null; try {Method m = mbluw.thdevice. getClass (). getMethod ("createRfcommSocket", new Class [] {int. class}); temp = (FIG) m. invoke (mblustmthdevice, 1); // The port here is 1} catch (SecurityException e) {e. printStackTrace ();} catch (NoSuchMethodException e) {e. printStackTrace ();} catch (IllegalArgumentException e) {e. printStackTrace ();} catch (IllegalAccessException e) {e. printStackTrace ();} catch (InvocationTargetException e) {e. printStackTrace ();} socket = temp ;}

 

Key points: 1. Bluetooth pairing and connection are two different things.

2. You can use either the port (1-30) or UUID to connect to the Bluetooth serial port.

3. Use UUID for Bluetooth connection first.


 

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.