Android蓝牙开发和BLE通讯Demo

源码地址

普通蓝牙:

  • 1. 配置蓝牙权限
    <!--允许程序连接配对过的蓝牙设备-->
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <!--允许程序进行发现和配对新的蓝牙设备-->
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
  • 2. 打开蓝牙
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {    //是否支持蓝牙
    return;
}
if (!mBluetoothAdapter.isEnabled()) {
    // 打开蓝牙方式一,直接打开
    mBluetoothAdapter.enable();
    // 打开蓝牙方式二,调用对话框打开: onActivityResult()提供打开成功的回调
// Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
// startActivityForResult(intent, 0);
    }
  • 3. 查找设备
IntentFilter intent = new IntentFilter();
intent.addAction(BluetoothDevice.ACTION_FOUND); // 用BroadcastReceiver来取得搜索结果
intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED); // 获取蓝牙设备的连接状态
intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
intent.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
intent.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, intent);
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            mDevices.add(bluetoothDevice);

        } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
            // 获取蓝牙设备的连接状态
            if (mBluetoothDevice == null) {
                return;
            }
            int connectState = mBluetoothDevice.getBondState();
            // 已配对
            if (connectState == BluetoothDevice.BOND_BONDED) {
                try {
                    show("客户端:开始连接:");
                    ClientThread clientConnectThread = new ClientThread(mBluetoothDevice);
                    clientConnectThread.start();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {  //搜索结束
            mDeviceAdapter.notifyDataSetChanged();
        }

    }
};
  • 4. 配对连接
BluetoothDevice bluetoothDevice = mDevices.get(position);
// 蓝牙配对
if (BluetoothDevice.BOND_NONE == bluetoothDevice.getBondState()) {
    mBluetoothDevice = bluetoothDevice;
    createBond(mDevices.get(position));
} else {// 蓝牙配对过,直接连接
    try {
        show("客户端:开始连接:");
        ClientThread clientConnectThread = new ClientThread(bluetoothDevice);
        clientConnectThread.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
/** * 配对设备 */
private void createBond(BluetoothDevice bluetoothDevice) {
    try {
        Method createBondMethod = BluetoothDevice.class.getMethod("createBond");
        createBondMethod.invoke(bluetoothDevice);
    } catch (Exception e) {
        e.getStackTrace();
    }
}
/** * 与设备解除配对 */
public boolean removeBond(BluetoothDevice bluetoothDevice) throws Exception {
    Method removeBondMethod = BluetoothDevice.class.getMethod("removeBond");
    Boolean returnValue = (Boolean) removeBondMethod.invoke(bluetoothDevice);
    return returnValue.booleanValue();
}

/** * 获取配对过的设备 */
private Set<BluetoothDevice> getBondedDevices() {
    pairedDevices = mBluetoothAdapter.getBondedDevices();
    for (BluetoothDevice device : pairedDevices) {
        Log.d(TAG, device.getName() + " " + device.getAddress());
    }
    return pairedDevices;
}
  • 5. 建立连接,socket通讯
/** * 开启客户端 */
private class ClientThread extends Thread {
    private BluetoothDevice bluetoothDevice;

    public ClientThread(BluetoothDevice bluetoothDevice) {
        this.bluetoothDevice = bluetoothDevice;
    }

    public void run() {
        try {
            //创建一个Socket连接:只需要服务器在注册时的UUID号
            mBluetoothSocket = bluetoothDevice.createRfcommSocketToServiceRecord(
                    UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));   //UUID被用于唯一标识一个服务,如文件传输服务,串口服务、打印机服务等
            //连接
            show("客户端:开始连接...");
            mBluetoothSocket.connect();
            show("客户端:连接成功");
            //启动接受数据
            show("客户端:启动接受数据");
            ReadThread mreadThread = new ReadThread(mBluetoothSocket);
            mreadThread.start();
        } catch (IOException e) {
            show("客户端:连接服务端异常!断开连接重新试一试");
            e.printStackTrace();
        }
    }
}
/** * 读取数据 */
private class ReadThread extends Thread {
    private BluetoothSocket bluetoothSocket;

    public ReadThread(BluetoothSocket bluetoothSocket) {
        this.bluetoothSocket = bluetoothSocket;
    }

    public void run() {
        byte[] buffer = new byte[1024];
        int bytes;
        InputStream is = null;
        try {
            is = bluetoothSocket.getInputStream();
            ToastUtils.show("客户端:获得输入流");
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        while (true) {
            try {
                if ((bytes = is.read(buffer)) > 0) {
                    byte[] buf_data = new byte[bytes];
                    for (int i = 0; i < bytes; i++) {
                        buf_data[i] = buffer[i];
                    }
                    String s = new String(buf_data);
                    ToastUtils.show("客户端:读取数据了" + s);
                }
            } catch (IOException e) {
                try {
                    is.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                break;
            }
        }
    }
}

BLE开发:

  • 1. 配置蓝牙权限
    <!--允许程序连接配对过的蓝牙设备-->
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <!--允许程序进行发现和配对新的蓝牙设备-->
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
     <!--required为true:应用只能在支持BLE的设备上安装运行;required为false:Android设备均可正常安装运行-->
    <uses-feature  android:name="android.hardware.bluetooth_le" android:required="true" />
  • 获取BLE设备

你可能感兴趣的:(蓝牙通讯,蓝牙BLE,蓝牙通讯demo,ble开发)