安卓中获取扫描特定类型的外围BLE设备蓝牙列表完整的用例
时间: 2024-03-11 19:48:54 浏览: 65
Android ble 蓝牙库
以下是一个安卓应用程序获取扫描特定类型的外围BLE设备蓝牙列表的完整用例:
```java
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.os.Handler;
import android.os.ParcelUuid;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private BluetoothAdapter mBluetoothAdapter;
private List<BluetoothDevice> mDeviceList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 获取BluetoothManager
final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
// 获取BluetoothAdapter
mBluetoothAdapter = bluetoothManager.getAdapter();
// 开始扫描
startScan();
}
private void startScan() {
// UUID 用于筛选特定类型的外围BLE设备
ParcelUuid uuid = new ParcelUuid(UUID.fromString("0000180F-0000-1000-8000-00805F9B34FB"));
// 开始扫描
mBluetoothAdapter.startLeScan(new UUID[]{uuid.getUuid()}, mLeScanCallback);
// 扫描 10 秒后停止
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
stopScan();
}
}, 10000);
}
private void stopScan() {
// 停止扫描
mBluetoothAdapter.stopLeScan(mLeScanCallback);
// 输出扫描结果
for (BluetoothDevice device : mDeviceList) {
Log.d(TAG, "Device Name: " + device.getName() + ", MAC Address: " + device.getAddress());
}
}
private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {
runOnUiThread(new Runnable() {
@Override
public void run() {
// 将扫描到的设备添加到列表中
if (!mDeviceList.contains(device)) {
mDeviceList.add(device);
}
}
});
}
};
}
```
在上述代码中,我们使用 `BluetoothAdapter` 和 `BluetoothManager` 获取蓝牙适配器,并使用 `startLeScan` 方法开始扫描。我们将 `ParcelUuid` 用于筛选特定类型的外围BLE设备,然后通过 `runOnUiThread` 将扫描到的设备添加到列表中。在扫描完成之后,我们通过 `stopLeScan` 停止扫描,并将扫描结果输出到日志中。
阅读全文