Android 蓝牙通信:客户端与服务端代码实现

提供 Android 平台上实现蓝牙通信的客户端和服务端代码示例。

服务端代码:

// ... 省略导入语句 ...

public class BluetoothServerActivity extends Activity {

    // ... 省略成员变量声明 ...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // ... 省略 Activity 初始化代码 ...

        // 初始化蓝牙适配器
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // 使蓝牙可见
        Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
        startActivity(discoverableIntent);

        // 创建蓝牙服务端套接字
        // ... 

        // 监听客户端连接请求
        // ...

        // 处理客户端连接
        // ...
    }

    // ... 省略其他方法 ...
}

客户端代码:

// ... 省略导入语句 ...

public class BluetoothClientActivity extends Activity {

    // ... 省略成员变量声明 ...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // ... 省略 Activity 初始化代码 ...

        // 初始化蓝牙适配器
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // 获取已配对设备列表
        Set pairedDevices = bluetoothAdapter.getBondedDevices();

        // 查找目标设备
        // ...

        // 创建蓝牙客户端套接字并连接到服务端
        // ...

        // 发送数据到服务端
        // ...

        // 接收服务端数据
        // ...
    }

    // ... 省略其他方法 ...
}

注意: 以上代码仅供参考,实际开发中需要根据具体需求进行修改和完善。

zip 文件大小:14.32MB