開發Android藍牙配對連接應用

jopen 10年前發布 | 74K 次閱讀 Android Android開發 移動開發

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

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

然后是tmp賦給BluetoothSocket,接著調用connect方法進行藍牙設備的連接。

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

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

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

方法2.通過UUID獲得BluetoothSocket,然后先根據mDevice.getBondState()進行判斷是否需要配對,最后執行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;  
        }  
    }  
}  </pre> <div class="dp-highlighter bg_java">

</div> </div>

接下來是調用的連接設備方法connectDevice():

</div> </div>

    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;  
        }  
    }  
}  </pre><a style="text-indent:0px;" title="派生到我的代碼片" href="/misc/goto?guid=4959550085812781111" target="_blank"></a></div>

</div> </div>

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

</div> </div>

    /**

     * 取得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;  
    }  </pre> <p></p>

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

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

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

來自:http://blog.csdn.net/jason0539/article/details/17782035

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!