Android: How to pair bluetooth devices programmati

2019-01-11 08:54发布

问题:

Please any one help me with pairing my android phone with other discovered phone programmatically ?

回答1:

Found the solution using reflection, I am doing this now as follows and it is working for me:

//For Pairing
private void pairDevice(BluetoothDevice device) {
    try {
        Log.d("pairDevice()", "Start Pairing...");
        Method m = device.getClass().getMethod("createBond", (Class[]) null);
        m.invoke(device, (Object[]) null);
        Log.d("pairDevice()", "Pairing finished.");
    } catch (Exception e) {
        Log.e("pairDevice()", e.getMessage());
    }
}


//For UnPairing
   private void unpairDevice(BluetoothDevice device) {
    try {
        Log.d("unpairDevice()", "Start Un-Pairing...");
        Method m = device.getClass().getMethod("removeBond", (Class[]) null);
        m.invoke(device, (Object[]) null);
        Log.d("unpairDevice()", "Un-Pairing finished.");
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
    }
}


回答2:

Can do it like:

public void pairDevice(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);
        getActivity().startActivityForResult(intent,0);


    }


回答3:

Did you set your permissions in the Android Manifest file?

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />