簡體   English   中英

Android:如何以編程方式配對藍牙設備?

[英]Android: How to pair bluetooth devices programmatically?

請任何人幫助我將我的Android手機與其他已發現的手機以編程方式配對?

使用反射找到解決方案,我現在正在執行此操作,如下所示,它對我有用:

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

可以這樣做:

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


    }

您是否在Android Manifest文件中設置了權限?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM