简体   繁体   中英

How to make a vcard/vcal Ndef message on Android

I'm new to Android coding, I'm interested in NFC technology. My first steps are focused on the Tag reading/write mode, currently I cannot see plenty of information on how to work with the Vcard/Vcal MIME types and NDEF Records/Messages.

It would be nice if someone can post some example code or better to point to a tutorial-like resource!

EDIT: This is a code that I've been using, it's messed up. With a few modifications I've been able to write plain text, and smart posters/urs data. Also to recall is that I'm using Type 2 NFC Tags, since the storage capacity is limited, I just want to save name & phone number on Vcards, or event name & date on Vcal records. Thanks!

public class VcardActivity extends Activity {

NfcAdapter adapter;
PendingIntent pendingIntent;
IntentFilter writeTagFilters[];
Tag tag;
Context ctx;
boolean writeMode;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_text);
    getActionBar().setDisplayHomeAsUpEnabled(true);

    ctx = this;
    Switch swWrite = (Switch) findViewById(R.id.switchWriteText);
    //final TextView msg = (TextView) findViewById(R.id.editText1);
    final String msg = "BEGIN:VCARD\n" +
            "VERSION:2.1\n" +
            "N:Gump;Forrest\n" +
            "FN:Forrest Gump\n" +
            "ORG:Bubba Gump Shrimp Co.\n" +
            "TITLE:Shrimp Man\n" +
            "TEL;WORK;VOICE111) 555-1212\n" +
            "TEL;HOME;VOICE404) 555-1212\n" +
            "ADR;WORK:;;100 Edge;Baytown;United\n" +
            "EMAIL;PREF;INTERNET:forrestgump@example.com\n " +
            "END:VCARD";
    swWrite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView,
                boolean isChecked) {
            if (isChecked) {
                try {
                    if (tag == null) {
                        Toast.makeText(ctx,
                                ctx.getString(R.string.error_detected),
                                Toast.LENGTH_SHORT).show();
                    } else {
                        write(msg, tag);
                        Toast.makeText(ctx,
                                ctx.getString(R.string.ok_writing),
                                Toast.LENGTH_LONG).show();
                    }
                } catch (IOException e) {
                    Toast.makeText(ctx,
                            ctx.getString(R.string.error_writing),
                            Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                } catch (FormatException e) {
                    Toast.makeText(ctx,
                            ctx.getString(R.string.error_writing),
                            Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                }

            }
        }
    });

    /* INTENT FILTER */
    adapter = NfcAdapter.getDefaultAdapter(this);
    pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
            getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
    IntentFilter tagDetected = new IntentFilter(
            NfcAdapter.ACTION_TAG_DISCOVERED);
    tagDetected.addCategory(Intent.CATEGORY_DEFAULT);
    writeTagFilters = new IntentFilter[] { tagDetected };
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_text, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        NavUtils.navigateUpFromSameTask(this);
        return true;
    }
    return super.onOptionsItemSelected(item);
}

private void write(String text, Tag tag) throws IOException,
        FormatException {

    NdefRecord[] records = { createRecord(text) };
    NdefMessage message = new NdefMessage(records);
    // Get an instance of Ndef for the tag.
    Ndef ndef = Ndef.get(tag);
    // Enable I/O
    ndef.connect();
    // Write the message
    ndef.writeNdefMessage(message);
    // Close the connection
    ndef.close();
}

private NdefRecord createRecord(String text)
        throws UnsupportedEncodingException {
    String msg = "BEGIN:VCARD\n" +
            "VERSION:2.1\n" +
            "N:Gump;Forrest\n" +
            "FN:Forrest Gump\n" +
            "ORG:Bubba Gump Shrimp Co.\n" +
            "TITLE:Shrimp Man\n" +
            "TEL;WORK;VOICE:55-1212\n" +
            "TEL;HOME;VOICE:55-1212\n" +
            "ADR;WORK:;;100 Edge;Ban;United\n" +
            "EMAIL;PREF;INTERNET:p@example.com\n " +
            "END:VCARD";

            byte[] textBytes = msg.getBytes();


            NdefRecord textRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA,
            "text/x-vCard".getBytes(), new byte[] {}, textBytes);

    return textRecord;
}

@Override
protected void onNewIntent(Intent intent) {
    if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
        tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        Toast.makeText(this,
                this.getString(R.string.ok_detection) + tag.toString(),
                Toast.LENGTH_LONG).show();
    }
}

@Override
public void onPause() {
    super.onPause();
    WriteModeOff();
}

@Override
public void onResume() {
    super.onResume();
    WriteModeOn();
}

private void WriteModeOn() {
    writeMode = true;
    adapter.enableForegroundDispatch(this, pendingIntent, writeTagFilters,
            null);
}

private void WriteModeOff() {
    writeMode = false;
    adapter.disableForegroundDispatch(this);
}

}

I've written an NDEF library which provides high-level (ie not byte-array) NDEF record/message representation, it also comes with a boilerplate project which demonstrates use on Android.

For getting to know the NDEF format itself, I have also written an Eclipse plugin which provides an graphical, file-based editor.

Cheers :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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