我正在开发一款搜索可发现设备并将其显示为按钮的应用。
当调用 startDiscovery()
时,根据我目前使用 BroadcastReceiver
和 ACTION_DISCOVERY_FINISHED< 调试它的方式,我会说它有 30% 的时间有效
.
我还使用 isDiscovering()
来测试是否调用了 startDiscovery()
函数但它返回 false。
有没有办法知道 startDiscovery()
是否调用成功?你能在我的代码中找出不会失败的东西吗?
Obs.: 我同时拥有 BLUETOOTH
和 BLUETOOTH_ADMIN
权限。
这是我的代码:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String Address;
// 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);
Address = device.getAddress();
System.out.println("Found Address: " + Address ); //DEBUG
//Do something with Address
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
System.out.println("Discovery finished");
}
}
};
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
MainActivity.mBluetoothAdapter.startDiscovery();
if (MainActivity.mBluetoothAdapter.isDiscovering()) {
System.out.println("Discovering..."); //DEBUG
}
}
虽然我有一些可用的可发现设备,但它们都不会触发 onReceive()
和 ACTION_FOUND
更新:我在应用程序运行时转到蓝牙设置下的“扫描”,但我无法扫描新设备。我禁用/启用蓝牙并返回应用程序,问题已解决。我不知道这是否表示适配器正忙或以某种方式停止。
最佳答案
我确认这个问题。
在某些手机上,您只需禁用/激活 BT。您可以通过编程方式进行操作
mBluetoothAdapter.disable();
mBluetoothAdapter.enable();
在某些手机上还不够(三星 S5)。为了检测它,我使用计时器,如果在超时结束时未收到 BT 广播状态的更改(BluetoothAdapter.ACTION_DISCOVERY_STARTED 或 BluetoothAdapter.ACTION_DISCOVERY_FINISHED)=> 它表明 BT 不工作。实际上我显示了建议用户重启手机的对话框。
关于android - Android 上的蓝牙 : Debuging startDiscovery(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22921632/