当前位置:   article > 正文

用NFC简化蓝牙配对并互相发送对方的蓝牙的MAC地址_通过nfc读取蓝牙mac地址

通过nfc读取蓝牙mac地址

本文的实现过程如下

Touch DeviceA发送DeviceA的MAC地址给DeviceB,DeviceB接收到DeviceA的MAC地址后,请求与之配对,配对成功后将DeviceB的MAC地址通过蓝牙发送给DeviceA

DevicA 发送本机地址

@Override
public NdefMessage createNdefMessage(NfcEvent event) {

    String text = ("Beam me up, Android!\n\n" +
            "Beam Time: " + System.currentTimeMillis());
    NdefMessage msg = new NdefMessage(
            new NdefRecord[]{
 createMime(//the other device recognise this APP and filter a activity by "application/vnd.com.example.huanghanqing.testnfc"
                    "application/vnd.com.example.huanghanqing.testnfc", getLocalBtAddr().getBytes())
                    //,NdefRecord.createApplicationRecord("com.example.android.beam")
            });
    return msg;
}
mNfcAdapter.setNdefPushMessageCallback(this, this);
DeviceB接收到对方地址并与之创建连接,返回数据

void processIntent(Intent intent) {
    Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
    // only one message sent during the beam
    NdefMessage msg = (NdefMessage) rawMsgs[0];
    // record 0 contains the MIME type, record 1 is the AAR, if present
    String bluetoothAddr = new String(msg.getRecords()[0].getPayload());
    textView.setText(bluetoothAddr);
    connectAndReturnBtaddr(bluetoothAddr);
}
private void connectAndReturnBtaddr(String bluetoothAddr) {

    try {
        try {
            if (bluetoothDevice == null) {
                bluetoothDevice = bluetoothAdapter.getRemoteDevice(bluetoothAddr);
            }
            if (bluetoothSocket == null) {
                bluetoothSocket = bluetoothDevice.createRfcommSocketToServiceRecord(MY_UUID);
                bluetoothSocket.connect();
                os = bluetoothSocket.getOutputStream();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (os != null) {
            os.write(bluetoothAdapte
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/314852
推荐阅读
相关标签
  

闽ICP备14008679号