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