首先澄清一下,这个解决方案是为更新版本的 API(15 或更高版本?)
我在另一篇文章中找到了答案(请参阅 Roldofo 在此处的答案)。这是我用详细代码重新组织的答案。
简而言之,您需要设置一个广播接收器来捕获 ACTION_PAIRING_REQUEST,然后以编程方式传递 PIN 并确认。
注册广播接收器:
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST);
getActivity().registerReceiver(mPairingRequestReceiver, filter);
接收器的定义:
private final BroadcastReceiver mPairingRequestReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(BluetoothDevice.ACTION_PAIRING_REQUEST)) {
try {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
int pin=intent.getIntExtra("android.bluetooth.device.extra.PAIRING_KEY", 1234);
//the pin in case you need to accept for an specific pin
Log.d(TAG, "Start Auto Pairing. PIN = " + intent.getIntExtra("android.bluetooth.device.extra.PAIRING_KEY",1234));
byte[] pinBytes;
pinBytes = (""+pin).getBytes("UTF-8");
device.setPin(pinBytes);
//setPairing confirmation if neeeded
device.setPairingConfirmation(true);
} catch (Exception e) {
Log.e(TAG, "Error occurs when trying to auto pair");
e.printStackTrace();
}
}
}
};
然后在您的活动或片段(无论您想在哪里启动配对),您可以调用以下定义的 pairDevice() 方法来调用配对尝试(这将生成一个 ACTION_PAIRING_REQUEST)
private void pairDevice(BluetoothDevice device) {
try {
Log.d(TAG, "Start Pairing... with: " + device.getName());
device.createBond();
Log.d(TAG, "Pairing finished.");
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}