动态注册广播接收器不起作用-BluetoothDevice.ACTION_FOUND [英] Register broadcast receiver dynamically does not work - BluetoothDevice.ACTION_FOUND
问题描述
使用Log
类跟踪运行时表明onReceive()
方法没有被调用,为什么?
Using Log
class to track Runtime show that onReceive()
methode does not called,why ?
动态注册广播接收器
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
}
推荐答案
您错过的是您需要启动设备发现
What you missed is that you need to start a device discovery
首先,获取蓝牙适配器
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
此后,您可以通过调用
mBtAdapter.startDiscovery();
您也应该在此处阅读详细信息,例如关于cancelDiscovery()
http://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#startDiscovery%28%29
You should read the details here as well, e.g. about cancelDiscovery()
http://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#startDiscovery%28%29
PS .此外,根据官方文档,建议使用context.getSystemService(Context.BLUETOOTH_SERVICE)
在API 18+上获取BluetoothAdapter.
P.S. Also, it is suggested to use context.getSystemService(Context.BLUETOOTH_SERVICE)
to get the BluetoothAdapter on API 18+, according to official doc.
要获取代表本地蓝牙适配器的BluetoothAdapter, 在JELLY_BEAN_MR1及更低版本上运行时,请调用静态 getDefaultAdapter()方法;在JELLY_BEAN_MR2及更高版本上运行时, 通过带有BLUETOOTH_SERVICE的getSystemService(Class)检索它.
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.
请注意,您需要startDiscovery()
的 BLUETOOTH_ADMIN 权限
Be reminded that you need BLUETOOTH_ADMIN permission to startDiscovery()
这篇关于动态注册广播接收器不起作用-BluetoothDevice.ACTION_FOUND的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!