I am currently trying to programmaticaly pair my Android device (4.4.2 KitKat) to a bluetooth dongle in a .NET project.
Normal pairing with user input (the pass key dialog) works, but I would like to bypass the user input.
After some reasearch ( here and here) I managed to come up with some code, but the dialog still appears.
Below I have my permisions:
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED" />
The minimum api level is set to 19, so I should have the Bluetooth privileged permission.
The code for pairing the specific device:
final String SERVER_MAC = "00:1A:7D:DA:71:07";
final BluetoothAdapter ba = BluetoothAdapter.getDefaultAdapter();
final ArrayList<BluetoothDevice> server = new ArrayList<>();
ba.startDiscovery();
BroadcastReceiver btReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice bd = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.d(TAG,"Found device: " + bd.getName() + " : " + bd.getAddress());
if(bd.getAddress().equals(SERVER_MAC)){
Log.d(TAG,"Server bluetooth found");
server.add(bd);
Log.d(TAG,"creating bond");
bd.createBond();
ba.cancelDiscovery();
}
}
else if(BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action)){
Log.d(TAG,"setting info");
setBluetoothPairingPin(server.get(0));
}
}
};
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(btReceiver, filter);
IntentFilter pairingRequest = new IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST);
registerReceiver(btReceiver,pairingRequest);
And the ACTION_PAIRING_REQUEST method:
byte[] pairingPin = "123456".getBytes();
try{
Log.d(TAG,"Trying to set pin");
bluetoothDevice.getClass().getMethod("setPin", byte[].class).invoke(bluetoothDevice,pairingPin);
Log.d(TAG,"Success setting pin");
try{
bluetoothDevice.getClass().getMethod("setPairingConfirmation", boolean.class).invoke(bluetoothDevice, true);
Log.d(TAG,"Success setting pairing confirmtion");
}
catch(Exception e){
Log.d(TAG,"Exception: " + e.getMessage());
}
}
catch(Exception e){
Log.d(TAG,"Exception 2: " + e.getMessage());
}
Any information would be helpful. Thanks!