android 忘记蓝牙配对,没有用户的Android蓝牙配对使用Android API输入Pin和Confirmation...

首先澄清一下,这个解决方案是为更新版本的API设计的(15或更高版本?)

我在另一篇文章中找到了答案(参见Roldofo在_1519056中的回答) . 这是我重新组织的答案和详细的代码 .

简而言之,您需要设置一个广播接收器来捕获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());

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值