I'm trying to get a list of disoverable bluetooth devices in android. I can get the devices and using an ArrayAdapter, populate a ListView of the devices. My question is, how do I save them to a list so I can use this information for another function? I've tried looking on the android developers site and all it has is the tutorial for the ListView. I've also looked for other tutorials or explanations and seem to be getting the wrong info.
My code is:
protected List<String> doInBackground(Void... arg0) {
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mBluetoothAdapter.startDiscovery();
// Create a BroadcastReceiver for ACTION_FOUND
final List<String> discoverableDevicesList = new ArrayList<String>();
final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
short rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
// Add the name and address to an array adapter to show in a ListView
System.out.println(device.getName());
discoverableDevicesList.add(device.getName() + "\n" + device.getAddress() + "\n" + rssi);
}
}
};
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
context.registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
return discoverableDevicesList;
}
It's probably something to do with the discover time associated with scanning for bluetooth devices, but I thought as each one was discovered I could just add it to the list? Has anyone come across something similar or have a possible solution? Much appreciated!