android開發之藍芽配對串連的方法

來源:互聯網
上載者:User

新年第一篇。

最近在做藍芽開鎖的小項目,手機去串連單片機總是出現問題,和手機的串連也不穩定,看了不少藍芽方面的文檔,做了個關於藍芽串連的小結。

在做android藍芽串口串連的時候一般會使用

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);}

然後是tmp賦給BluetoothSocket,接著調用connect方法進行藍牙裝置的串連。

可是 BluetoothSocket 的connect方法本身就會報很多異常錯誤。

以下根據對藍芽開發的一點研究可通過以下方法解決:

方法1.先進行藍芽自動配對,配對成功,通過UUID獲得BluetoothSocket,然後執行connect()方法。

方法2.通過UUID獲得BluetoothSocket,然後先根據進行判斷是否需要配對,最後執行connnect()方法。

 

    private class ConnectThread extends Thread {        String macAddress = "";        public ConnectThread(String mac) {            macAddress = mac;        }        public void run() {            connecting = true;            connected = false;            if(mBluetoothAdapter == null){                mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();            }            mBluetoothDevice = mBluetoothAdapter.getRemoteDevice(macAddress);            mBluetoothAdapter.cancelDiscovery();            try {                socket = mBluetoothDevice.createRfcommSocketToServiceRecord(uuid);                            } catch (IOException e) {                // TODO Auto-generated catch block                //e.printStackTrace();                Log.e(TAG, "Socket", e);            }                         //adapter.cancelDiscovery();            while (!connected && connetTime <= 10) {                                connectDevice();            }            // 重設ConnectThread             //synchronized (BluetoothService.this) {               //ConnectThread = null;            //}        }        public void cancel() {            try {                socket.close();                socket = null;            } catch (Exception e) {                e.printStackTrace();            } finally {                connecting = false;            }        }    }

接下來是調用的串連裝置方法connectDevice():

protected void connectDevice() {          try {              // 串連建立之前的先配對              if (mBluetoothDevice.getBondState() == BluetoothDevice.BOND_NONE) {                  Method creMethod = BluetoothDevice.class                          .getMethod("createBond");                  Log.e("TAG", "開始配對");                  creMethod.invoke(mBluetoothDevice);              } else {              }          } catch (Exception e) {              // TODO: handle exception              //DisplayMessage("無法配對!");              e.printStackTrace();          }          mBluetoothAdapter.cancelDiscovery();          try {              socket.connect();              //DisplayMessage("串連成功!");             //connetTime++;            connected = true;        } catch (IOException e) {              // TODO: handle exception              //DisplayMessage("串連失敗!");            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;        }      }


 

方法3.利用反射通過連接埠獲得BluetoothSocket,然後執行connect()方法。

    private class ConnectThread extends Thread {        String macAddress = "";        public ConnectThread(String mac) {            macAddress = mac;        }        public void run() {            connecting = true;            connected = false;            if(mBluetoothAdapter == null){                mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();            }            mBluetoothDevice = mBluetoothAdapter.getRemoteDevice(macAddress);            mBluetoothAdapter.cancelDiscovery();            initSocket();                                     //adapter.cancelDiscovery();            while (!connected && connetTime <= 10) {                try {                    socket.connect();                    connected = true;                } catch (IOException e1) {                    connetTime++;                    connected = false;                    // 關閉 socket                    try {                        socket.close();                        socket = null;                    } catch (IOException e2) {                        //TODO: handle exception                          Log.e(TAG, "Socket", e2);                    }                } finally {                    connecting = false;                }                //connectDevice();            }            // 重設ConnectThread             //synchronized (BluetoothService.this) {               //ConnectThread = null;            //}        }        public void cancel() {            try {                socket.close();                socket = null;            } catch (Exception e) {                e.printStackTrace();            } finally {                connecting = false;            }        }    }

接下來是初始化並得到BluetoothSocket的方法

/**     * 取得BluetoothSocket     */    private void initSocket() {        BluetoothSocket temp = null;        try {                        Method m = mBluetoothDevice.getClass().getMethod(                    "createRfcommSocket", new Class[] { int.class });            temp = (BluetoothSocket) m.invoke(mBluetoothDevice, 1);//這裡連接埠為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;    }

 

要點:1.藍芽配對和串連是兩回事,不可混為一談。

   2.藍芽串口串連可通過連接埠 (1-30)和UUID兩種方法進行操作。

   3.通過UUID進行藍芽串連最好先進行配對操作。


 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.