在Android中检测蓝牙低功耗设备

8

我是一名Android应用程序开发的初学者。我已经尝试阅读文档,但没有取得任何进展(在Android的教程中,如StartLeScan()等功能已被弃用,等等...)

是否有一个简单的函数返回蓝牙设备列表?

类似于getDevices() ->(设备列表)?

谢谢

4个回答

15

基本上这取决于你所针对的安卓版本。因为API在棒棒糖(21)中有一些变化。

在你的活动中,获取蓝牙适配器。

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

别忘了在你的清单文件中添加权限。

    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
    <uses-permission android:name="android.permission.BLUETOOTH"/>

谢谢!REQUEST_ENABLE_BT是什么?另外,在“// get the discovered device as you wish”中放什么?文档对于如何在“onLeScan”和“onScanResult”方法中访问设备很困惑。你能举个例子,说明我如何访问找到的设备的标识符、MAC地址等或一些名称字符串吗? - kmn
REQUEST_ENABLE_BT是您期望在onActivityResult中返回的某个整数。在onActivityResult()中,您可以检查结果是否针对该特定请求(启用bt)。关于Mac地址。你有BluetoothDevice。您可以调用device.getAddress()或任何其他可用的方法http://developer.android.com/reference/android/bluetooth/BluetoothDevice.html - DanM

2
如果您使用的API等级低于21,则会发现StartLeScan已被弃用。在Android Lollipop中,引入了带有新扫描设置特性的StartLeScan()。您可以使用以下代码来扫描BLE设备。
ScanSettings.Builder scanSettingsBuilder = new ScanSettings.Builder();
scanSettingsBuilder.setScanMode(ScanSettings.SCAN_MODE_LOW_POWER);
scanSettings = scanSettingsBuilder.build();

BluetoothScanCallback mScanCallback = new BluetoothScanCallback();
mBluetoothUtils.getBluetoothAdapter().getBluetoothLeScanner()
                .startScan(scanFilters, scanSettings, mScanCallback);

1
如果你花时间撰写解释,为什么不花时间完整地呈现它呢?“scanSettings”是什么? - Nactus
@Nactus扫描设置用于更改蓝牙适配器的扫描功率。该API出现在API级别21中。使用代码,您可以轻松了解我们正在使用该API的目的。 - johny kumar

0

我也曾为这个问题苦恼了几个小时,后来在官方文档中找到了答案。
你需要了解三个类和方法:ScanCallback、BluetoothLeScanner和ScanResult。
//我的水平太低了,无法发布链接...
您可以在Android开发者网站上查看,页面右侧将显示“添加于API级别21”

这是我的代码,从这些项目修改而来。

//declare    
private BluetoothLeScanner mBluetoothLeScanner;  
mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();

//start and stop scan
mBluetoothLeScanner.startScan(mScanCallback);
mBluetoothLeScanner.stopScan(mScanCallback);

//Scan call back function
private ScanCallback mScanCallback = new ScanCallback() {
    @Override
    public void onScanResult(int callbackType, ScanResult result) {
         super.onScanResult(callbackType, result);
         mLeDeviceListAdapter.addDevice(result.getDevice());
         mLeDeviceListAdapter.notifyDataSetChanged();
    }
};

我的Gradle:

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"

    defaultConfig {
        applicationId "com.polkapolka.bluetooth.le"
        minSdkVersion 21
        targetSdkVersion 22
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}

这段代码在我的手机上运行良好,我的手机是API 21的版本。希望对你有所帮助。

0

我一直在尝试使用BLE扫描,直到我从Nordic库中找到了最简单的解决方案。

在你的build.gradle文件中添加一行:

dependencies {
  ....
  compile 'no.nordicsemi.android.support.v18:scanner:1.0.0'
}

并使用BluetoothLeScannerCompat:

import no.nordicsemi.android.support.v18.scanner.BluetoothLeScannerCompat;

...
BluetoothLeScannerCompat scanner = BluetoothLeScannerCompat.getScanner();
scaner.startScan(new ScanCallback { ...});

而且这个库会完成所有的工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接