有2种扫描方式:
//Device scan callback Lollipop and above private ScanCallback generateScanCallback(){ if(apiVersion> Build.VERSION_CODES.KITKAT) { ScanCallback mScanCallback = new ScanCallback() { @Override public void onScanResult(int callbackType, ScanResult result) { super.onScanResult(callbackType, result); final BluetoothDevice device = result.getDevice(); getActivity().runOnUiThread(new Runnable() { @Override public void run() { Log.e(TAG, "running scan " + device.getAddress()); if (device.getAddress().equals(mDeviceAddress)) { Log.e(TAG, "device founded, trying to connect"); scanLeDevice(false); Intent gattServiceIntent = new Intent(mContext, BluetoothLeService.class); mContext.bindService(gattServiceIntent, mServiceConnection, mContext.BIND_AUTO_CREATE); mIndicationText.setText(mContext.getString(R.string.waiting)); } } }); } }; return mScanCallback; } return null; } // Device scan callback KITKAT and below. private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() { @Override public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { Log.e(TAG,"running scan "+device.getType()); if(device.getAddress().equals(mDeviceAddress)){ Log.e(TAG, "device founded, trying to connect"); scanLeDevice(false); Intent gattServiceIntent = new Intent(mContext, BluetoothLeService.class); mContext.bindService(gattServiceIntent, mServiceConnection, mContext.BIND_AUTO_CREATE); mIndicationText.setText(mContext.getString(R.string.waiting)); } } }); } };
然后:
if(apiVersion> Build.VERSION_CODES.KITKAT) { scanner = mBluetoothAdapter.getBluetoothLeScanner(); // Device scan callback LOLLIPOP scanner.startScan(generateScanCallback()); } else { mBluetoothAdapter.startLeScan(mLeScanCallback); }
您可以根据需要自定义您的扫描方法,但您必须知道有2个扫描方法一个用于android 5及更高版本,另一个用于其他android OS