简体   繁体   English

在Android上将联系人写入NFC标签

[英]Writing a contact to NFC tag on Android

Is there any tutorial or example that explains how I can make my android program write a specific contact (name and phone number) to NFC tag. 是否有任何教程或示例说明如何使我的android程序将特定联系人(姓名和电话号码)写入NFC标签。 So when the user touches the tag with his phone, it saves the contact to his phone contacts? 因此,当用户用手机触摸标签时,会将联系人保存到手机联系人中吗?

Yes. 是。 Using the VCARD type. 使用VCARD类型。

Inside your NFC event intent handler, use this method to build your NdefRecord: 在您的NFC事件意图处理程序中,使用此方法来构建NdefRecord:

public NdefRecord createVcardRecord(String name, String org, String tel, String email) 
        throws UnsupportedEncodingException {

    String payloadStr = "BEGIN:VCARD" +"\n"+ 
                        "VERSION:2.1" +"\n" + 
                        "N:;" + name + "\n" + 
                        "ORG:"+org+"\n"+ 
                        "TEL:"+tel+"\n"+
                        "EMAIL:"+email+"\n
                        "+"END:VCARD";
    byte[] uriField = payloadStr.getBytes(Charset.forName("US-ASCII"));
    byte[] payload = new byte[uriField.length + 1];
    System.arraycopy(uriField, 0, payload, 1, uriField.length);
    NdefRecord nfcRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, 
            "text/vcard".getBytes(), 
            new byte[0], 
            payload);

    return nfcRecord;
}

Then add the record to your records array: 然后将记录添加到记录数组:

NdefRecord[] records = new NdefRecord[1];
records[0] = createVcardRecord("Henry", "Henry's Company", "0412345678", "henry@domain.com");

Pass the records array into an NdefMessage and you are ready to write: 将records数组传递到NdefMessage中,就可以编写了:

NdefMessage message = new NdefMessage(records);
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
writeToTag(message, tag); // your tag writing function

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

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