android蓝牙低功耗(BLE)onlescan

时间:2015-01-22 10:09:30

标签: android bluetooth

我正在尝试在android中执行BLE应用程序,但我无法弄清楚为什么没有调用onLeScan()函数。

private void scanLeDevice(final boolean enable) {
   Log.d(Tag,"in scanLeDevice");
    if (enable) {
        // Stops scanning after a pre-defined scan period.
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mScanning = false;
                mBluetoothAdapter.stopLeScan(mLeScanCallback);
                invalidateOptionsMenu();
            }
        }, SCAN_PERIOD);

        Log.d(Tag,"Scanning Done");
        mScanning = true;
        mBluetoothAdapter.startLeScan(mLeScanCallback);
    } else {
        mScanning = false;
        mBluetoothAdapter.stopLeScan(mLeScanCallback);
    }
    invalidateOptionsMenu();
}


// Device scan callback.
private BluetoothAdapter.LeScanCallback mLeScanCallback =
        new BluetoothAdapter.LeScanCallback() {

    @Override
    public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
        Log.e(Tag,"Scan device rssi is " + rssi);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mLeDeviceListAdapter.addDevice(device);
                mLeDeviceListAdapter.notifyDataSetChanged();
            }
        });
    }
};

logcat的:

 01-22 15:34:02.449:     D/MainActivity(32531):      in scanLeDevice    
    01-22 15:34:02.449:     D/MainActivity(32531):      Scanning Done
    01-22 15:34:02.449:     D/BluetoothAdapter(32531):  startLeScan(): null
    01-22 15:34:02.453:     D/BluetoothAdapter(32531):  onClientRegistered() - status=0 clientIf=5
    01-22 15:34:09.005:     D/MainActivity(32531):      in scanLeDevice
    01-22 15:34:09.005:     D/BluetoothAdapter(32531):  stopLeScan()

2 个答案:

答案 0 :(得分:1)

检查AndroidManifest.xml文件中是否包含此内容:

<service android:name=".bluetooth.BluetoothLeService" android:enabled="true" />

此外,您应该通过BluetoothManager初始化蓝牙适配器:

if (!mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
    Toast.makeText(mContext, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
    return false;
}

// Initializes a Bluetooth adapter.  For API level 18 and above, get a reference to
// BluetoothAdapter through BluetoothManager.
final BluetoothManager bluetoothManager =
        (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();

答案 1 :(得分:0)

您需要在AndroidManifest.xml中同时拥有以下权限才能扫描设备:

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