Error Error - 6 months ago 241
Android Question

Register broadcast receiver dynamically does not work - BluetoothDevice.ACTION_FOUND

Using

Log
class to track Runtime show that
onReceive()
methode does not called,why ?

Register broadcast receiver dynamically

private void discoverDevices () {
Log.e("MOHAB","BEFORE ON RECEIVE");

mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
Log.e("MOHAB","ON RECEIVE");
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);
// Add the name and address to an array adapter to show in a ListView
Bluetooth b = new Bluetooth(device.getName(),device.getAddress());
list.add(b);
}
}
};
Log.e("MOHAB","create intentFilter");
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy

}

Answer

What you missed is that you need to start a device recovery

First, get the bluetooth adapter

BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();

After that, you start the discovery by calling

mBtAdapter.startDiscovery();

You should read the details here as well, e.g. about cancelDiscovery() http://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#startDiscovery%28%29

P.S. Also, it is suggested to use context.getSystemService(Context.BLUETOOTH_SERVICE) to get the BluetoothAdapter on API 18+, according to official doc.

To get a BluetoothAdapter representing the local Bluetooth adapter, when running on JELLY_BEAN_MR1 and below, call the static getDefaultAdapter() method; when running on JELLY_BEAN_MR2 and higher, retrieve it through getSystemService(Class) with BLUETOOTH_SERVICE.

Edit: Be reminded that you need BLUETOOTH_ADMIN permission to startDiscovery()

Comments