接上篇,接下来我们就来看一下如何扫描到周围的手机蓝牙,主要是经典蓝牙
// 广播接收发现蓝牙设备
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
Log.i("Lyb", "开始扫描...");
}
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device != null) {
if (device.getType() != BluetoothDevice.DEVICE_TYPE_LE)
Log.i("Lyb", "discovery==" + "设备名:" + device.getName() + "\n设备地址:" + device.getAddress());
}
}
if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
Log.i("Lyb", "扫描结束.");
//
}
}
};
然后
// 注册广播接收器。
// 接收蓝牙发现
IntentFilter filterFound = new IntentFilter(BluetoothDevice.ACTION_FOUND);
getPageContext().registerReceiver(mReceiver, filterFound);
IntentFilter filterStart = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
getPageContext().registerReceiver(mReceiver, filterStart);
IntentFilter filterFinish = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
getPageContext().registerReceiver(mReceiver, filterFinish);
try {
Method setDiscoverableTimeout = BluetoothAdapter.class.getMethod("setDiscoverableTimeout", int.class);
setDiscoverableTimeout.setAccessible(true);
Method setScanMode = BluetoothAdapter.class.getMethod("setScanMode", int.class, int.class);
setScanMode.setAccessible(true);
setDiscoverableTimeout.invoke(BluetoothAdapter.getDefaultAdapter(), Integer.MAX_VALUE);
setScanMode.invoke(BluetoothAdapter.getDefaultAdapter(), BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE, Integer.MAX_VALUE);
} catch (Exception e) {
e.printStackTrace();
}
最后
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mBluetoothAdapter.startDiscovery();
好了这样就能获取到最近的蓝牙设备了