写一个Android蓝牙连接传输数据的代码
时间: 2024-06-16 11:03:13 浏览: 8
当然,我可以为您提供一个简单的示例代码来介绍如何在Android中使用蓝牙进行连接和数据传输。以下是一个基本的蓝牙连接和数据传输的代码示例:
1. 添加权限到AndroidManifest.xml文件中:
```xml
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
```
2. 在Activity中初始化蓝牙适配器和相关变量:
```java
private BluetoothAdapter bluetoothAdapter;
private BluetoothDevice bluetoothDevice;
private BluetoothSocket bluetoothSocket;
private OutputStream outputStream;
private InputStream inputStream;
// 初始化蓝牙适配器
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
```
3. 检查设备是否支持蓝牙:
```java
if (bluetoothAdapter == null) {
// 设备不支持蓝牙
return;
}
```
4. 打开蓝牙:
```java
if (!bluetoothAdapter.isEnabled()) {
Intent enableBluetoothIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetoothIntent, REQUEST_ENABLE_BLUETOOTH);
}
```
5. 搜索并连接蓝牙设备:
```java
// 搜索蓝牙设备
bluetoothAdapter.startDiscovery();
// 监听搜索到的蓝牙设备
BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// 根据设备名称或地址判断是否为目标设备
if (device.getName().equals("目标设备名称") || device.getAddress().equals("目标设备地址")) {
bluetoothDevice = device;
bluetoothAdapter.cancelDiscovery();
// 连接蓝牙设备
connectToDevice();
}
}
}
};
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(bluetoothReceiver, filter);
```
6. 连接到蓝牙设备:
```java
private void connectToDevice() {
UUID uuid = UUID.fromString("00001101-1000-8000-00805F9B34FB"); // SPP通信协议的UUID
try {
bluetoothSocket = bluetoothDevice.createRfcommSocketToServiceRecord(uuid);
bluetoothSocket.connect();
outputStream = bluetoothSocket.getOutputStream();
inputStream = bluetoothSocket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
```
7. 发送数据:
```java
String message = "Hello, Bluetooth!";
try {
outputStream.write(message.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
```
8. 接收数据:
```java
byte[] buffer = new byte[1024];
int bytes;
try {
bytes = inputStream.read(buffer);
String receivedMessage = new String(buffer, 0, bytes);
} catch (IOException e) {
e.printStackTrace();
}
```
这是一个简单的蓝牙连接和数据传输的示例代码。您可以根据您的具体需求进行修改和扩展。如果您有任何进一步的问题,请随时提问。