可以通过以下步骤来获取BluetoothDevice对象:
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(receiver, filter);
其中,receiver是实现了BroadcastReceiver接口的对象,用于处理广播接收器接收到的信息。 3. 启动设备的发现过程:
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
bluetoothAdapter.startDiscovery();
private final BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//使用device对象进行相关操作
}
}
};
获取到的BluetoothDevice对象可以用于进行连接等操作。 需要注意的是,在使用完搜索设备的操作后,应该取消广播接收器的注册,以免浪费资源:
unregisterReceiver(receiver);