android studio如何进行蓝牙通信
时间: 2023-10-26 11:45:03 浏览: 90
Android Studio可以使用Android的蓝牙API进行蓝牙通信。您可以通过创建BluetoothAdapter对象并调用其方法来扫描和连接其他蓝牙设备。使用BluetoothSocket类可以进行数据传输。此外,Android还提供了许多蓝牙通信库和框架,如BlueZ、Bluedroid等。
相关问题
androidstudio 低耗蓝牙通信
### 如何在 Android Studio 中实现低功耗蓝牙 (BLE) 通信
#### 权限配置
为了使应用程序能够访问设备的蓝牙功能,在 `AndroidManifest.xml` 文件中需声明必要的权限:
```xml
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<!-- For API level >= 23 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
```
对于运行时权限请求,当目标 SDK 版本大于等于 23 时,还需要动态获取位置权限[^4]。
#### 初始化 BluetoothAdapter 和 BluetoothLeScanner
创建一个用于管理蓝牙连接的对象实例,并通过它来启动扫描过程:
```java
BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
BluetoothLeScanner bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
```
#### 执行 BLE 设备扫描
定义回调函数监听发现到的新设备并处理扫描结果。可以设定过滤条件只接收特定类型的广播包数据。
```java
ScanCallback leScanCallback = new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
Log.i("BLE", "Discovered BLE Device: " + result.getDevice().getName());
}
};
bluetoothLeScanner.startScan(leScanCallback); // 开始扫描
// 建议设置超时机制停止长时间无响应的扫描任务
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(() -> bluetoothLeScanner.stopScan(leScanCallback), SCAN_PERIOD);
```
#### 连接至远程 GATT Server
一旦找到目标设备,则尝试建立与其之间的安全会话通道。
```java
BluetoothDevice device = ... ; // 获取具体设备对象
device.connectGatt(this /* context */, false /* autoConnect */,
gattCallback /* 回调接口 */ );
```
其中 `gattCallback` 是自定义类实现了 `BluetoothGattCallback` 接口的方法集合,用来监控和服务交互状态变化事件。
#### 发送/接收特征值读取命令
成功关联后即可向远端服务器发送指令查询指定服务下的属性信息或执行其他操作。
```java
public class SampleGattCallbacks extends BluetoothGattCallback {
private final static String UUID_HEART_RATE_MEASUREMENT =
"00002a37-0000-1000-8000-00805f9b34fb";
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,
int newState) {
super.onConnectionStateChange(gatt, status, newState);
if (newState == BluetoothProfile.STATE_CONNECTED){
gatt.discoverServices(); // 查询可用的服务列表
}else{
gatt.close();
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
super.onServicesDiscovered(gatt, status);
List<BluetoothGattService> services = gatt.getServices();
for (BluetoothGattService service : services) {
BluetoothGattCharacteristic characteristic =
service.getCharacteristic(UUID.fromString(UUID_HEART_RATE_MEASUREMENT));
if(characteristic != null){
gatt.readCharacteristic(characteristic);
}
}
}
}
```
上述代码片段展示了如何利用官方API完成基本的数据交换逻辑[^1]。
基于Androidstudio的蓝牙通信代码
以下是一个基于 Android Studio 的蓝牙通信示例代码:
1. 在 AndroidManifest.xml 文件中添加以下权限:
```xml
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
```
2. 在 layout 文件夹中创建一个布局文件 activity_main.xml:
```xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<Button
android:id="@+id/button_search"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Search Devices"/>
<ListView
android:id="@+id/list_devices"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/button_send"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send Data"/>
<EditText
android:id="@+id/edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
```
3. 创建一个 BluetoothAdapter 对象以进行蓝牙通信。在 MainActivity.java 文件中添加以下代码:
```java
public class MainActivity extends AppCompatActivity {
private BluetoothAdapter bluetoothAdapter;
private ArrayAdapter<String> devicesArrayAdapter;
private ListView listView;
private EditText editText;
private Button buttonSearch, buttonSend;
private BluetoothDevice device;
private BluetoothSocket socket;
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// Check if the device supports Bluetooth
if (bluetoothAdapter == null) {
Toast.makeText(getApplicationContext(), "Bluetooth not supported", Toast.LENGTH_LONG).show();
finish();
return;
}
// Check if Bluetooth is enabled
if (!bluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, 0);
}
// Initialize UI components
listView = findViewById(R.id.list_devices);
editText = findViewById(R.id.edit_text);
buttonSearch = findViewById(R.id.button_search);
buttonSend = findViewById(R.id.button_send);
devicesArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
listView.setAdapter(devicesArrayAdapter);
buttonSearch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
searchDevices();
}
});
buttonSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sendData();
}
});
}
// Search for Bluetooth devices
private void searchDevices() {
devicesArrayAdapter.clear();
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
devicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
// Start discovery of new devices
bluetoothAdapter.startDiscovery();
registerReceiver(discoveryReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
// Send data to the connected device
private void sendData() {
String data = editText.getText().toString();
try {
OutputStream outputStream = socket.getOutputStream();
outputStream.write(data.getBytes());
outputStream.flush();
Toast.makeText(getApplicationContext(), "Data sent", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Error sending data", Toast.LENGTH_LONG).show();
}
}
// Broadcast receiver for discovering new devices
private final BroadcastReceiver discoveryReceiver = 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);
devicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
};
// Connect to the selected device
private void connectToDevice(String deviceAddress) {
device = bluetoothAdapter.getRemoteDevice(deviceAddress);
try {
socket = device.createRfcommSocketToServiceRecord(MY_UUID);
socket.connect();
Toast.makeText(getApplicationContext(), "Connected to " + device.getName(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Error connecting to device", Toast.LENGTH_LONG).show();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(discoveryReceiver);
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
4. 您可以在 MainActivity.java 文件中添加其他方法,例如取消搜索、断开连接等。请注意,此示例代码仅用于演示目的,您需要根据自己的需求进行修改和完善。
阅读全文