[英]Android Bluetooth API not finding any devices
I am trying to implement a Bluetooth device discovery function in my app. 我正在尝试在我的应用程序中实现蓝牙设备发现功能。 I have implemented the proposed way to do it with a
BluetoothAdapter
and a BroadcastReceiver
like so: 我已经实现了使用
BluetoothAdapter
和BroadcastReceiver
的建议方法,如下所示:
My Activity (discover() is called in onCreate):
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
BluetoothAdapter mBluetoothAdapter;
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
//Finding devices
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
//discovery starts, we can show progress dialog or perform other tasks
testDevice("Start discover");
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
//discovery finishes, dismis progress dialog
testDevice("Discovery finished");
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//bluetooth device found
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
testDevice("Found device " + device.getName());
}
}
};
public void discover() {
this.mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
mBluetoothAdapter.startDiscovery();
}
public void testDevice(String msg) {
Toast.makeText(this, msg,
Toast.LENGTH_LONG).show();
}
}
In my manifest I have the following permissions: 在清单中,我具有以下权限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
The result is me getting two toasts: "Start discovery" and 10sec later "Discovery finished". 结果是我得到了两次祝酒:“开始发现”和10秒后的“发现完成”。 Never a device is found.
找不到设备。 I have tested on Samsung S9+, Sansumg Tab A, and Motorola something (with Bluetooth on).
我已经在Samsung S9 +,Sansumg Tab A和Motorola上进行了测试(已打开蓝牙)。
Is there something I am not doing wright or is there any known problems I don't know? 有没有我没有做的事情,还是有我不知道的已知问题?
Pure speculation on my end, but in case you're running on API level 23 + (and likely you are), you need to dynamically ask for permissions, not just declare them in manifest. 我纯粹是猜测,但是如果您正在API级别23 +上运行(并且可能是),则需要动态地请求权限,而不仅仅是在清单中声明它们。 Either use
RxPermissions
or ContextCompat.checkSelfPermission
. 使用
RxPermissions
或ContextCompat.checkSelfPermission
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.