在Android上,如果蓝牙的StartDiscovery方法不起作用,并且无法获取任何结果,同时BroadcastReceiver也不起作用,可能是由于以下几个原因:
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
// 设备不支持蓝牙
} else {
if (!bluetoothAdapter.isEnabled()) {
// 蓝牙未开启,使用enable方法开启蓝牙
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
然后在BluetoothReceiver类中,继承BroadcastReceiver并重写onReceive方法来处理相应的广播事件。
public class BluetoothReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
// 蓝牙开始扫描
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
// 蓝牙扫描结束
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// 发现蓝牙设备
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// 处理蓝牙设备
}
}
}
private static final int REQUEST_PERMISSION = 1;
private void requestPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
REQUEST_PERMISSION);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == REQUEST_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// 权限已授予,执行蓝牙扫描
startDiscovery();
} else {
// 权限被拒绝
}
}
}
通过以上解决方法,您可以尝试解决Android上蓝牙StartDiscovery不起作用,无法获取任何结果,BroadcastReceiver不起作用的问题。
上一篇:Android上的蓝牙延迟补偿
下一篇:Android上的链接回退。