我正在尝试构建一个Bluetoothscanner。 但是startDiscovery()没有启动。我已经包含了权限。
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
我的代码是:
final BluetoothManager mBluetoothManager =
(BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = mBluetoothManager.getAdapter();
mBluetoothAdapter.disable();
onoff.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.enable();
onoff.setChecked(true);
}
else {
mBluetoothAdapter.disable();
onoff.setChecked(false);
}
if(!mBluetoothAdapter.isDiscovering()){
Log.e("Searching?: ", "is not searching");
mBluetoothAdapter.startDiscovery();
Log.d("SearchingStatus: ", "startDiscovery() started!" );
Log.e("Searching?", String.valueOf(mBluetoothAdapter.isDiscovering()));
}
}
});
我的上一个日志如下:
Searching?: false
答案 0 :(得分:1)
BluetoothAdapter.enable是一个异步调用:它将立即返回,客户端应该侦听ACTION_STATE_CHANGED以获得有关后续适配器状态更改的通知,请参阅https://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#enable()
如果您注释掉所有对BluetoothAdapter.enable / BluetoothAdapter.disable的呼叫并确保启用蓝牙(来自设置 - >蓝牙),那么在启动应用之前是否可以正常工作?
我会检查mBluetoothAdapter.startDiscovery()的返回值,如果返回false,则返回Log.e。