Import Android.app.activity;import Android.content.contentresolver;import Android.content.context;import Android.net.uri;import Android.nfc.ndefmessage;import Android.nfc.ndefrecord;import Android.nfc.NfcAdapter;import Android.nfc.nfcevent;import Android.provider.contactscontract.contacts;import Android.provider.contactscontract.profile;import Android.util.log;import Java.io.bytearrayoutputstream;import Java.io.ioexception;import java.io.inputstream;/** * This class implements sharing the currently displayed * contact to Another device using NFC. NFC sharing is only * enabled while the activity is in the foreground and resumed. * When a NFC link is established, {@link #createMessage} * 'll be called to create the data to being sent over the link, * Which is a vCard in this case. */public class Nfchandler implements Nfcadapter.createndefmessagecallback {private static final String TAG = "contactn Fchandler "; private static final String Profile_lookup_key = "Profile"; PrivaTe final Context Mcontext; Private final Uri Mcontacturi; /* Register NFC handler. This should is called in activities ' OnCreate (), or similar methods */public static void register (activity activity, U Ri Contacturi) {nfcadapter adapter = Nfcadapter.getdefaultadapter (Activity.getapplicationcontext ()); if (adapter = = null) {return; NFC not available on this device} adapter.setndefpushmessagecallback (new Nfchandler (activity, Contacturi ), activity); } public Nfchandler (context context, Uri Contacturi) {mcontext = context; Mcontacturi = Contacturi; } @Override Public ndefmessage createndefmessage (Nfcevent event) {Contentresolver resolver = Mcontext.getcon Tentresolver (); if (Mcontacturi! = null) {final String LookupKey = Uri.encode (Mcontacturi.getpathsegments (). Get (2)); Final Uri Shareuri; TODO find out where to get the constant from, or find another of determining this. if (Lookupkey.equals (Profile_lookup_key)) {Shareuri = Profile.CONTENT_VCARD_URI.buildUpon (). Appendqueryparameter (Contacts.query_parameter_vcard_no_photo, "true"). Build (); } else {Shareuri = Contacts.CONTENT_VCARD_URI.buildUpon (). Appendpath (LookupKey). Appendqueryparameter (Contacts.query_parameter_vcard_no_photo, "true"). Build (); } bytearrayoutputstream ndefbytes = new Bytearrayoutputstream (); byte[] buffer = new byte[1024]; int R; try {inputstream Vcardinputstream = Resolver.openinputstream (Shareuri); while ((r = vcardinputstream.read (buffer)) > 0) {ndefbytes.write (buffer, 0, R); } Ndefrecord record = Ndefrecord.createmime ("Text/x-vcard", Ndefbytes.tobytearray ()); ReturN New Ndefmessage (record); } catch (IOException e) {log.e (TAG, "IOException creating vcard."); return null; }} else {LOG.W (TAG, "No contact URI to share."); return null; } }}
The code called by the activity side:
Nfchandler.register (this, Mlookupuri);
The above two pieces of code, from the Android source inside the contacts
work_space/packages/apps/contacts/
Android NFC Transfer Contact VCF