【发布时间】:2015-08-25 09:08:10
【问题描述】:
在下面的代码中,当调用btnDiscoverListener 时,会执行“else”语句并调用“btAdapter.startDiscovery();”然后调用“getBTDeviceExtras();”。
在“btAdapter.startDiscovery()”中,它使广播接收器收到有关开始发现相邻设备的通知,
如果发现邻居设备,广播接收器将进入“BluetoothDevice.ACTION_FOUND”。
我预计当“btnDiscoverListener”被调用时,“getBTDeviceExtras()”直到“btAdapter.startDiscovery();”才会被执行彻底结束!!
但正如您在下面发布的输出中看到的那样,首先调用了“getBTDeviceExtras()”。
谁能解释这是如何以及为什么会发生的。
代码:
private OnClickListener btnDiscoverListener = new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (btAdapter.isDiscovering()) {
return;
} else {
btAdapter.startDiscovery();
getBTDeviceExtras();
}
}
};
private void getBTDeviceExtras() {
Log.d(TAG, LogAnd.show("getBTDeviceExtras", "called."));
if (this.stateExtDevice != null) {
Log.d(TAG, LogAnd.show("getBTDeviceExtras", "called1."));
adapter.add(this.stateExtDevice.getName()+"\n"+this.stateExtDevice.getAddress()+"\n"+this.stateExtDevice.getBondState()
+"\n"+this.stateExtDevice.getType()+"\n"+this.stateExtDevice.getUuids());
adapter.notifyDataSetChanged();
} else {
Log.d(TAG, LogAnd.show("getBTDeviceExtras", "called2."));
tvStatus.setText("BT-Receiver received not notifications");
}
}
代码:
08-25 10:54:14.305: D/MainActivity(2624): -> getBTDeviceExtras:called.
08-25 10:54:14.315: D/MainActivity(2624): -> getBTDeviceExtras:called2.
08-25 10:54:14.325: D/MainActivity(2624): -> onReceive:BluetoothAdapter.ACTION_DISCOVERY_STARTED
08-25 10:54:15.155: D/MainActivity(2624): -> onReceive:BluetoothDevice.ACTION_FOUND
08-25 10:54:27.155: D/MainActivity(2624): -> onReceive:BluetoothAdapter.ACTION_DISCOVERY_FINISHED
【问题讨论】:
-
startDiscovery()是异步的,这意味着它只会调用startDiscovery(),然后它会在后台运行。你需要等待它以某种方式完成。 -
@Detilium 你能告诉我你怎么知道 startdiscovery 是异步的??
-
Fomr this SO 线程(答案 1)编辑:Android Developer
标签: android android-intent broadcastreceiver intentfilter