socket 入門 (二)藍牙

private UUID sppUUID;   
private BluetoothDevice mBluetoothDevice;
// 藍牙 socket
private BluetoothSocket mSocket = null;
/**
 *
 * @param device: 需要連接的wifi,從廣播中掃描藍牙。
 */
public void connect(BluetoothDevice device, OnConnectListener listener) {
    this.mBluetoothDevice = device;
   
    if (device.getUuids() == null || device.getUuids().length == 0) {
        this.sppUUID = UUID.fromString(UUID_BT_DEFAULT);
    } else {
        this.sppUUID = device.getUuids()[0].getUuid();//UUID.fromString("00001101-0000-8000-00805f9b34fb");
    }
    connect(true);
}

 

private void connect(final boolean needCallback) {
    new Thread(() -> doConnect(needCallback)).start();
}
/**
開始連接
*/
private void doConnect(final boolean needCallback) {
    try {
        if (mBluetoothDevice != null) {
            BluetoothSocket tmp = mBluetoothDevice.createInsecureRfcommSocketToServiceRecord(sppUUID);
            mSocket = tmp;
        }
        //http://www.android-doc.com/guide/topics/connectivity/bluetooth.html
        // Cancel discovery because it will slow down the connection
        BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
        if (mSocket != null) {
            mSocket.connect();
            mSocket.isConnected;
        }
        Log.e(TAG, "doConnect: success");
        if (needCallback) {
            connectHandler.sendEmptyMessage(1);
        }

    } catch (IOException e) {
        
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章