BLE android 5.0 崩溃

BLE android 5.0 Crash

我在使用 android 和 BLE 时遇到问题,每次我进行扫描时我的应用程序都会崩溃,但我不知道原因。我使用 startLeScan() 这可能是原因吗? 这是我的代码示例。

这里是我初始化的地方 api 18

//API 18
private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

    @Override
    public void onLeScan(final BluetoothDevice device, int rssi,
            byte[] scanRecord) {

        Sensortag sensortag = new Sensortag(device, SensortagScanner.this,
                mSensortagScannerCallback);

        synchronized (this) {
            for (Sensortag other : mDiscoveredDevices) {
                if (sensortag.getName().equals(other.getName())) {
                    Log.i("SensortagScanner",
                            "Discovered duplicate device: "
                                    + other.getName());
                    return;
                }
            }
        }

        mDiscoveredDevices.add(sensortag);
        Log.i("SensortagScanner",
                "Discovered a device named " + device.getName() + ".");
        mCallback.onSensorDiscovered(sensortag);
    }
};

这里是我初始化 ScanCall 的地方,看起来似乎是错误的错误 java nulle 异常 //API 21

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void initScanCallback() {

    if (scanCallback != null)
        return;
    this.scanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
            // Do whatever you want
        }

        @Override
        public void onBatchScanResults(List<ScanResult> results) {
            super.onBatchScanResults(results);
            Log.d(TAG, "Batch scan results: ");
            for (ScanResult result : results) {
                Log.d(TAG, "Batch scan result: " + result.toString());
                // Do whatever you want
            }
        }

        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
            // scanListener.onScanFinished();
            Log.d(TAG, "Scan failed");
        }
    };
}

这是我开始扫描的地方

    @Override
    public void startScan(SensorScannerCallback callback) {

    mCallback = callback;

    if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
        callback.onScannerUnavailable(this);
        return;
    }

    mHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
            stopScan();
        }
    }, SCAN_PERIOD);

    Log.i("SensortagScanner", "Starting scan...");

    mScanning = true;

    // ////////////POUR API 21//////////////
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        mBluetoothAdapter.getBluetoothLeScanner().startScan(scanCallback);
    }

    // /////////POUR API <18////////////////
    else {
        mBluetoothAdapter.startLeScan(mLeScanCallback);
    }
}

尝试使用 Android 5 的方法,如下面的代码片段所示。它可能会有所帮助。 如果没有,请显示更多您的代码以及崩溃发生时出现的错误。

首先,你需要一个回调,所以根据 android 版本正确初始化它。

private void initScanCallback(){
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        initCallbackLollipop();
    }else{
        initScanCallbackSupport();
    }
}

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void initCallbackLollipop(){
    if(scanCallback != null) return;
    this.scanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
            //Do whatever you want
        }

        @Override
        public void onBatchScanResults(List<ScanResult> results) {
            super.onBatchScanResults(results);
            Log.d(TAG, "Batch scan results: ");
            for (ScanResult result: results){
                Log.d(TAG, "Batch scan result: " + result.toString());
                //Do whatever you want
            }
        }

        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
            Log.d(TAG, "Scan failed");
        }
    };
}

private void initScanCallbackSupport(){
    if(callback != null) return;
    this.callback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(final BluetoothDevice device, int rssi, final byte[] scanRecord) {
            String address = device.toString();
            String name = device.getName();

            // parse uuids according to another Whosebug post
            //List<UUID> uuids = parseUuids(scanRecord);

            // TODO Compare detected UUIDs with the uuidFilter
            //for(UUID discUUID : uuids)
            //    for(UUID uuid : BLEScanService.this.uuidFilter)
            //        if(discUUID.equals(uuid))
                        BLEScanService.this.scanListener.onDeviceScanned(address, name, uuids, rssi);
        }
    };
}

然后就可以按照android版本开始扫描了:

public void startScanWithServices(List<String> uuidFilters){
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        scanLollipop(uuidFilters);
    }else{
        scanSupport(uuidFilters);
    }

    // Store filters for later filtering
    int size = uuidFilters.size();
    this.uuidFilter = new ArrayList<UUID>();
    for(int i = 0; i<size; i++){
        this.uuidFilter.add(UUID.fromString(uuidFilters.get(i)));
    }

    if(BuildConfig.DEBUG) Log.d(TAG, "BLE Scan started");
}

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void scanLollipop(List<String> uuidFilters){
    if(scanCallback == null)
        initCallbackLollipop();

    List<ScanFilter> filters = new ArrayList<ScanFilter>();

    ScanSettings settings = new ScanSettings.Builder()
            .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) // or BALANCED previously
            .setReportDelay(0)
            .build();

    bluetoothAdapter.getBluetoothLeScanner().startScan(filters, settings, scanCallback);
    //bluetoothAdapter.getBluetoothLeScanner().startScan(scanCallback);
}

private void scanSupport(List<String> uuidFilters){
    if(callback == null)
        initScanCallbackSupport();

    //start scan
    //boolean success = bluetoothAdapter.startLeScan(uuids, callback);

    boolean success = bluetoothAdapter.startLeScan(callback);

    //check scan success
    if(!success) {
        if(BuildConfig.DEBUG) Log.d(TAG, "BLE Scan failed");
        scanListener.onScanFinished();
    }
}

然后你可以像这样停止扫描:

public void stopScan(){
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        // Stop scan and flush pending scan
        bluetoothAdapter.getBluetoothLeScanner().flushPendingScanResults(scanCallback);
        bluetoothAdapter.getBluetoothLeScanner().stopScan(scanCallback);
    }else{
        bluetoothAdapter.stopLeScan(callback);
    }

    if(BuildConfig.DEBUG) Log.d(TAG, "BLE Scan stopted");
}

检查您的清单文件。您应该拥有这些权限

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