蓝牙控制app Android studio代码
时间: 2024-04-21 14:07:04 浏览: 95
【AndroidStudio】经典蓝牙+BLE蓝牙搜索APP
4星 · 用户满意度95%
以下是一个简单的蓝牙控制 Android 应用程序的代码示例:
1. 首先,在 AndroidManifest.xml 文件中添加以下权限:
```
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-feature android:name="android.hardware.bluetooth" />
```
2. 在你的 Activity 中声明以下变量:
```
private BluetoothAdapter mBluetoothAdapter;
private BluetoothDevice mDevice;
private BluetoothSocket mSocket;
private OutputStream mOutputStream;
private InputStream mInputStream;
```
3. 初始化 BluetoothAdapter
```
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// 设备不支持蓝牙
Toast.makeText(this, "设备不支持蓝牙", Toast.LENGTH_SHORT).show();
return;
}
```
4. 搜索并连接蓝牙设备
```
private void searchAndConnect() {
Intent intent = new Intent(this, DeviceListActivity.class);
startActivityForResult(intent, REQUEST_CONNECT_DEVICE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CONNECT_DEVICE && resultCode == RESULT_OK) {
String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
mDevice = mBluetoothAdapter.getRemoteDevice(address);
new ConnectThread().start();
}
}
private class ConnectThread extends Thread {
public void run() {
try {
mSocket = mDevice.createRfcommSocketToServiceRecord(MY_UUID);
mSocket.connect();
mOutputStream = mSocket.getOutputStream();
mInputStream = mSocket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
// 连接失败
return;
}
// 连接成功
}
}
```
5. 发送数据
```
private void sendData(String data) {
if (mOutputStream == null) {
// 未连接设备
return;
}
try {
mOutputStream.write(data.getBytes());
} catch (IOException e) {
e.printStackTrace();
// 发送失败
}
}
```
6. 接收数据
```
private class ReceiveThread extends Thread {
public void run() {
byte[] buffer = new byte[1024];
int bytes;
while (true) {
try {
bytes = mInputStream.read(buffer);
String data = new String(buffer, 0, bytes);
// 处理接收到的数据
} catch (IOException e) {
e.printStackTrace();
// 接收失败
break;
}
}
}
}
```
注意:这只是一个简单的示例代码,实际应用程序需要更多的错误处理和逻辑来满足需求。
阅读全文