Я пытался соединить свой андроид с BLE
устройством.Проблема в том, что когда я вызываю запрос на сопряжение, появляется диалоговое окно.Но когда я ввел свой пароль, он не соединяется или 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);
Реализация broadcastReciever.
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 () после обнаружения устройства.