//以前的方式
BluetoothManager mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothAdapter mBluetoothAdapter = mBluetoothManager.getAdapter();
mBluetoothAdapter.startLeScan(mLeScanCallback);
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
runOnUiThread(new Runnable() {
@Override
public void run() {
mLeDeviceListAdapter.addDevice(device);//mLeDeviceListAdapter封装了BlutoothDevice
mLeDeviceListAdapter.notifyDataSetChanged();
}
});
}
};
/*
LeDeviceListAdapter的私有属性ArrayList mLeDevices中取得device
BluetoothDevice getDevice(int position) {
return mLeDevices.get(position);
}
*/
final BluetoothDevice device = getDevice(int poisition);
/*
final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);//这是这么个情况,第一个页面已经扫描到了BluetoothDevice,把他的deviceName和Mac地址传入第二个页面,可以直接用这种方式获得一个BlueToothDevice
*/
mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
//现在的方式
BluetoothManager blutoothManager=(BluetoothManager)context.getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothAdapter mBluetoothAdapter=blutoothManager.getAdapter();
BluetoothLeScanner mBluetoothLeScanner=mBluetoothAdapter.getBluetoothLeScanner();
mBluetoothLeScanner.startScan(buildScanFilters(), buildScanSettings(), mScanCallback);//这三个参数需要自己写方法实现,我们重点关注mScanCallback的实现
//在mScanCallback的实现里面,得到的ScanResult封装了BluetoothDevice
private class SampleScanCallback extends ScanCallback {
@Override
public void onBatchScanResults(List<ScanResult> results) {
super.onBatchScanResults(results);
for (ScanResult result : results) {
mAdapter.add(result);
}
mAdapter.notifyDataSetChanged();
}
@Override
public void onScanResult(int callbackType, ScanResult result) {
super.onScanResult(callbackType, result);
mAdapter.add(result);
mAdapter.notifyDataSetChanged();
}
@Override
public void onScanFailed(int errorCode) {
super.onScanFailed(errorCode);
Toast.makeText(getActivity(), "Scan failed with error: " + errorCode, Toast.LENGTH_LONG)
.show();
}
}
转载于:https://www.cnblogs.com/sunupo/p/10301278.html