我是 Android 应用程序开发的初学者。我已经尝试阅读文档,但一无所获(Android 教程中的函数,例如 StartLeScan()
已被弃用,等等...)
是否有一个返回蓝牙设备列表的简单函数?
类似于 getDevices()
->(设备列表)?
谢谢
最佳答案
基本上,这取决于您所针对的 Android 版本。因为 api 在 lollipop (21) 中发生了一些变化。
在您的 Activity 中,获取蓝牙适配器
BluetoothManager bm = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE)
BluetoothAdapter mBluetoothAdapter = bm.getAdapter();
// Ensures Bluetooth is available on the device and it is enabled. If not,
// displays a dialog requesting user permission to enable Bluetooth.
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
然后你应该检查你的目标是哪个android版本
int apiVersion = android.os.Build.VERSION.SDK_INT;
if (apiVersion > android.os.Build.VERSION_CODES.KITKAT){
BluetoothLeScanner scanner = mBluetoothAdapter.getBluetoothLeScanner();
// scan for devices
scanner.startScan(new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
// get the discovered device as you wish
// this will trigger each time a new device is found
BluetoothDevice device = result.getDevice();
}
});
} else {
// targetting kitkat or bellow
mBluetoothAdapter.startLeScan(new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
// get the discovered device as you wish
}
});
// rest of your code that will run **before** callback is triggered since it's asynchronous
不要忘记在 list 中添加权限
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.BLUETOOTH"/>
关于android - 在 Android 中检测蓝牙 Le 设备,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28365260/