帮我写一个蓝牙接收APP
时间: 2024-04-30 11:18:50 浏览: 164
好的,以下是一个简单的蓝牙接收APP的示例代码,你可以根据自己的需求进行修改和扩展:
```
public class BluetoothReceiverActivity extends AppCompatActivity {
private BluetoothAdapter bluetoothAdapter;
private BluetoothSocket btSocket;
private ConnectedThread connectedThread;
private TextView textView;
private static final UUID BT_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static final String DEVICE_ADDRESS = "XX:XX:XX:XX:XX:XX";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth_receiver);
textView = findViewById(R.id.textView);
// 获取BluetoothAdapter实例
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// 检查设备是否支持蓝牙
if (bluetoothAdapter == null) {
Toast.makeText(this, "设备不支持蓝牙", Toast.LENGTH_SHORT).show();
finish();
return;
}
// 检查蓝牙是否已开启
if (!bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
} else {
connectToDevice();
}
}
private void connectToDevice() {
// 获取远程设备
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(DEVICE_ADDRESS);
// 创建BluetoothSocket连接
try {
btSocket = device.createRfcommSocketToServiceRecord(BT_UUID);
} catch (IOException e) {
Toast.makeText(this, "创建BluetoothSocket连接失败", Toast.LENGTH_SHORT).show();
finish();
return;
}
// 连接到BluetoothSocket
try {
btSocket.connect();
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
// ignore
}
Toast.makeText(this, "连接失败", Toast.LENGTH_SHORT).show();
finish();
return;
}
// 开启接收线程
connectedThread = new ConnectedThread(btSocket);
connectedThread.start();
}
private class ConnectedThread extends Thread {
private final InputStream inputStream;
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
try {
tmpIn = socket.getInputStream();
} catch (IOException e) {
Toast.makeText(BluetoothReceiverActivity.this, "获取输入流失败", Toast.LENGTH_SHORT).show();
}
inputStream = tmpIn;
}
public void run() {
byte[] buffer = new byte[1024];
int bytes;
while (true) {
try {
bytes = inputStream.read(buffer);
final String message = new String(buffer, 0, bytes);
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText(message);
}
});
} catch (IOException e) {
break;
}
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (connectedThread != null) {
connectedThread.interrupt();
}
if (btSocket != null) {
try {
btSocket.close();
} catch (IOException e) {
// ignore
}
}
}
}
```
请注意,上述代码仅为示例代码,尚未进行完整测试和优化,需要根据实际情况进行修改和完善。
阅读全文