我试图将我的 android 与 BLE
设备配对。问题是当我调用配对请求 Activity 时,对话框出现了。但是当我输入我的密码时,它没有被配对或者 onActivityResult
没有被调用。那么如何配对成功呢?
private void startBluetoothPairing(BluetoothDevice device) {
String ACTION_PAIRING_REQUEST = "android.bluetooth.device.action.PAIRING_REQUEST";
Intent intent = new Intent(ACTION_PAIRING_REQUEST);
String EXTRA_DEVICE = "android.bluetooth.device.extra.DEVICE";
intent.putExtra(EXTRA_DEVICE, device);
String EXTRA_PAIRING_VARIANT = "android.bluetooth.device.extra.PAIRING_VARIANT";
int PAIRING_VARIANT_PIN = 0;
intent.putExtra(EXTRA_PAIRING_VARIANT, PAIRING_VARIANT_PIN);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
((Activity) appContext).startActivityForResult(intent,1);
}
OnActivityResult 未被调用。
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.v("TAG","Bluetooth Device!!");
if (requestCode == 1) {
if (resultCode == Activity.RESULT_OK) {
BluetoothDevice bluetoothDevice = data.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Parcel parcel = Parcel.obtain();
data.getParcelableExtra(BluetoothDevice.EXTRA_PAIRING_KEY).writeToParcel(parcel, 0);
byte[] bytes = parcel.marshall();
parcel.recycle();
bluetoothDevice.setPin(bytes);
bluetoothDevice.createBond();
}
}
}
问题已解决: 更新代码:
在应用程序启动期间注册了 broadCasterReciever
IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST);
intentFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
appContext.getApplicationContext().registerReceiver(broadCastReceiver,intentFilter);
广播接收器的实现。
private String BLE_PIN= "000012";
private BroadcastReceiver broadCastReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action))
{
BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
bluetoothDevice.setPin(BLE_PIN.getBytes());
Log.e("TAG","Auto-entering pin: " + BLE_PIN);
}
}
};
我在发现设备后调用了 device.createBond()。
最佳答案
这是我正在使用的,对我来说效果很好。
与设备配对
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
BluetoothActivity.this.registerReceiver(mReceiver, filter);
device.createBond();
BroadcastReceiver 检查设备是否配对
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String name = device.getName();
String address = device.getAddress();
if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
//Device Paired
}
}
}
};
在onDestroy中注销接收者
BluetoothActivity.this.unregisterReceiver(mReceiver);
关于android - 与 BLE 的蓝牙配对在 Android 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56555271/