我正在尝试在我的应用程序中实现蓝牙设备发现功能。我已经实现了使用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秒后“发现完成”。从未找到过设备。我已经测试了三星S9 +,Sansumg Tab A和摩托罗拉的东西(蓝牙开启)。
有什么我不做的事还是有任何我不知道的已知问题?
我的结论是纯粹的猜测,但是如果你在API级别23 +上运行(可能你是),你需要动态地请求权限,而不仅仅是在清单中声明它们。要么使用RxPermissions
,要么使用ContextCompat.checkSelfPermission
。