我正在尝试在我的应用程序中实现蓝牙设备发现功能。我已经实现了使用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();
}
}
在清单中,我具有以下权限:
<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" />
结果是我举杯两次:“开始发现”和10秒后的“发现完成”。找不到设备。我已经在Samsung S9 +,Sansumg Tab A和Motorola上进行了测试(已打开蓝牙)。
有没有我在做的事,还是有我不知道的已知问题?
答案 0 :(得分:1)
纯粹是推测,但如果您运行的是API级别23 +(可能是),则需要动态地请求权限,而不仅仅是在清单中声明它们。使用RxPermissions
或ContextCompat.checkSelfPermission
。