In this question, @nhoxbypass provides this method for the purpose of adding found Bluetooth devices to a list:
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Message msg = Message.obtain();
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
//Found, add to a device list
}
}
};
However, I do not understand how a reference to the found device can be obtained, how can this be done?
I do not have permission to comment on the original question, so I have chosen to extend it here.
The Bluetooth guide in the Android documentation explains this:
In order to receive information about each device discovered, your application must register a BroadcastReceiver for the ACTION_FOUND intent. The system broadcasts this intent for each device. The intent contains the extra fields EXTRA_DEVICE and EXTRA_CLASS, which in turn contain a BluetoothDevice and a BluetoothClass, respectively.
This sample code is included as well:
@Override protected void onCreate(Bundle savedInstanceState) { ... // Register for broadcasts when a device is discovered. IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); registerReceiver(mReceiver, filter); } // Create a BroadcastReceiver for ACTION_FOUND. private final BroadcastReceiver mReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothDevice.ACTION_FOUND.equals(action)) { // Discovery has found a device. Get the BluetoothDevice // object and its info from the Intent. BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); String deviceName = device.getName(); String deviceHardwareAddress = device.getAddress(); // MAC address } } };
If you are working with Bluetooth on Android, I suggest to read that guide carefully. Then read it one more time ;-)
From the ACTION_FOUND documentation:
Always contains the extra fields
EXTRA_DEVICEandEXTRA_CLASS. Can contain the extra fieldsEXTRA_NAMEand/orEXTRA_RSSIif they are available.
EXTRA_DEVICE can be used to obtain the BluetoothDevice that was found via code like:
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
来源:https://stackoverflow.com/questions/49352868/obtaining-a-list-of-available-bluetooth-devices-on-android