简体   繁体   English

如何以编程方式配对蓝牙设备 Android

[英]How to pair Bluetooth device programmatically Android

I am developing an application where I want to connect a Bluetooth device main issue is I don't want user to enter required pin instead application should do that by himself...I don't have any connection related issue...Only want to insert and complete pin authentication process by application itself.我正在开发一个应用程序,我想连接蓝牙设备的主要问题是我不希望用户输入所需的 pin 而应用程序应该自己做...我没有任何与连接相关的问题...只想要由应用程序本身插入并完成 pin 认证过程。

I found following code I am sure it is working but not sure on how to add pin in this code??我发现以下代码我确定它可以工作但不确定如何在此代码中添加引脚?

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());
        }
    }

Does anyone know how to enter pin in above code or any similar code to solve problem.. Thank You有谁知道如何在上面的代码或任何类似的代码中输入 pin 来解决问题..谢谢

How can I avoid or dismiss Android's Bluetooth pairing notification when I am doing programmatic pairing? 在进行编程配对时,如何避免或关闭 Android 的蓝牙配对通知?

This seems to give you the answer, with the pin entering and all.这似乎给了你答案,别针进入等等。 It involves sending .setPin() whenever you get the message.它涉及在您收到消息时发送 .setPin()。

So, I had this question, if someone needs the answer to this working in android 4.4.2.所以,我有这个问题,如果有人需要在 android 4.4.2 中工作的答案。

 IntentFilter filter = new IntentFilter(
                "android.bluetooth.device.action.PAIRING_REQUEST");


        /*
         * Registering a new BTBroadcast receiver from the Main Activity context
         * with pairing request event
         */
        registerReceiver(
                new PairingRequest(), filter);

And the code for the Receiver.以及接收器的代码。

  public static class PairingRequest extends BroadcastReceiver {
        public PairingRequest() {
            super();
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("android.bluetooth.device.action.PAIRING_REQUEST")) {
                try {
                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    int pin=intent.getIntExtra("android.bluetooth.device.extra.PAIRING_KEY", 0);
                    //the pin in case you need to accept for an specific pin
                    Log.d("PIN", " " + intent.getIntExtra("android.bluetooth.device.extra.PAIRING_KEY",0));
                    //maybe you look for a name or address
                    Log.d("Bonded", device.getName());
                    byte[] pinBytes;
                    pinBytes = (""+pin).getBytes("UTF-8");
                    device.setPin(pinBytes);
                    //setPairing confirmation if neeeded
                    device.setPairingConfirmation(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

And in the manifest file.并在清单文件中。

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

And the broadcastReceiver.和广播接收器。

 <receiver android:name=".MainActivity$PairingRequest">
                <intent-filter>
                    <action android:name="android.bluetooth.device.action.PAIRING_REQUEST" />
                    <action android:name="android.bluetooth.device.action.PAIRING_CANCEL" />
                </intent-filter>
</receiver>

How to set the pin code has been answered above (and that helped me).上面已经回答了如何设置密码(这对我有帮助)。 Yet, I share my simple code below which works with Android 6:然而,我在下面分享了适用于 Android 6 的简单代码:

BluetoothAdapter mBTA = BluetoothAdapter.getDefaultAdapter();
if (mBTA.isDiscovering()) mBTA.cancelDiscovery();
mBTA.startDiscovery();
...

/** In a broadcast receiver: */

if (BluetoothDevice.ACTION_FOUND.equals(action)) { // One device found.

    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
    Log.d(TAG, "Start Pairing... with: " + device.getName());
    device.createBond();
}

// If you want to auto-input the pin#:
else if (BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action)){

                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    device.setPin("1234".getBytes());
}

Try this code:试试这个代码:

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);
    context.startActivity(intent);
}

Intent intent = new Intent(BluetoothDevice.ACTION_PAIRING_REQUEST);
intent.putExtra(EXTRA_DEVICE, device);
int PAIRING_VARIANT_PIN = 272;
intent.putExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT, PAIRING_VARIANT_PIN);
sendBroadcast(intent);

Intent intent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS);
startActivityForResult(intent, REQUEST_PAIR_DEVICE);

I hope this helps我希望这有帮助

Reference: http://pastebin.com/N8dR4Aa1参考: http : //pastebin.com/N8dR4Aa1

Register a BluetoothDevice.ACTION_PAIRING_REQUEST receiver onCreate()注册一个BluetoothDevice.ACTION_PAIRING_REQUEST接收器 onCreate()

val pairingRequestFilter = IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST)
        registerReceiver(pairingReceiver, pairingRequestFilter)

on receiver set your pin using setPin() and call abortBroadcast()在接收器上使用setPin()设置您的 pin 并调用abortBroadcast()

val PAIRING_PIN=1234

private var pairingReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            val action = intent!!.action
            if (BluetoothDevice.ACTION_PAIRING_REQUEST == action) {
                val device: BluetoothDevice? =intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
                val type =intent.getIntExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT, BluetoothDevice.ERROR)
                if (type == BluetoothDevice.PAIRING_VARIANT_PIN) {
                    device?.setPin(PAIRING_PIN.toByteArray())
                    abortBroadcast()
                }
            }
        }
    }

Don't forget to unregister receiver on onDestroy()不要忘记在onDestroy()上取消注册接收器

override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(pairingReceiver)
    }

if it doesn't work for you, try setting hight priority to receiver如果它不适合您,请尝试为接收器设置高优先级

val pairingRequestFilter = IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST)          
pairingRequestFilter.priority = IntentFilter.SYSTEM_HIGH_PRIORITY - 1
            registerReceiver(pairingReceiver, pairingRequestFilter)

Also you can register a receiver with BluetoothDevice.ACTION_BOND_STATE_CHANGED to read status of pairing您也可以使用BluetoothDevice.ACTION_BOND_STATE_CHANGED注册接收器以读取配对状态

val filter = IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED)
        registerReceiver(receiver, filter)

Try this,试试这个,

BluetoothDevice device = intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE");
device.getClass().getMethod("setPairingConfirmation", boolean.class).invoke(device, true);
device.getClass().getMethod("cancelPairingUserInput", boolean.class).invoke(device);
    BluetoothSocket bluetoothSocket = null;
    try {
        bluetoothSocket = device.createRfcommSocketToServiceRecord(UUID.fromString(UUID_DIVING));
    } catch (IOException e) {
        Log.i("Bluetooth", "IOException = " + e.getMessage());
        e.printStackTrace();
    }

    try {
        byte[] pin = (byte[]) BluetoothDevice.class.getMethod("convertPinToBytes", String.class).invoke(BluetoothDevice.class, "0000");
        Method m = device.getClass().getMethod("setPin", byte[].class);
        m.invoke(device, (Object) pin);
        device.getClass().getMethod("setPairingConfirmation", boolean.class).invoke(device, true);
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
        Log.i("Bluetooth", "IOException = " + e.getMessage());
        e.printStackTrace();
    }

    try {
        if (bluetoothSocket != null) {
            bluetoothSocket.connect();
            Log.i("Bluetooth", "bluetoothSocket.connect() ");
            InputStream inputStream = bluetoothSocket.getInputStream();
            OutputStream outputStream = bluetoothSocket.getOutputStream();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

bluetoothDevice.createBond method , you can use for paring bluetoothDevice.createBond 方法,可用于配对

For checking paring status , you have to register broadcast receiver BluetoothDevice.ACTION_BOND_STATE_CHANGED要检查配对状态,您必须注册广播接收器 BluetoothDevice.ACTION_BOND_STATE_CHANGED

In your receiver class, you can check blueToothDevice.getBondState在您的接收器类中,您可以检查 blueToothDevice.getBondState

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM