蓝牙通信app android studio例子
时间: 2023-05-19 21:03:56 浏览: 177
你可以在Android Studio中使用Bluetooth API来创建一个蓝牙通信应用程序。以下是一个简单的例子:
1. 首先,你需要在你的AndroidManifest.xml文件中添加以下权限:
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
2. 在你的Activity中,你需要声明一个BluetoothAdapter对象:
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
3. 然后,你需要检查设备是否支持蓝牙:
if (bluetoothAdapter == null) {
// Device doesn't support Bluetooth
}
4. 如果设备支持蓝牙,你需要确保蓝牙已经打开:
if (!bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
5. 然后,你需要扫描周围的蓝牙设备:
bluetoothAdapter.startDiscovery();
6. 当你发现一个设备时,你可以使用BluetoothDevice对象来连接它:
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(MY_UUID);
socket.connect();
7. 一旦连接成功,你可以使用InputStream和OutputStream对象来发送和接收数据:
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
这是一个简单的例子,你可以根据你的需求进行修改和扩展。
阅读全文
相关推荐















