Androidプログラマへの道 〜 Moonlight 明日香 〜 - URI Recordを作成する
NFCのデータ交換フォーマット(NDEF : NFC Data Exchange Format)は, NFC準拠のデバイスとNFCカード/タグとの間で通信を行う際の共通データフォーマットとして定義されている.
その中の1つに, RTD(Record Type Definition) URIフォーマットというのがある.
名前オフセットサイズ説明
Identifier code01 byteURI識別子コード
URI field1NURIの残り(UTF-8)
DecimalHexプロトコル
00x00N/A
10x01http://www.
20x02https://www.
30x03http://
40x04https://
50x05tel:
60x06mailto:
:::

RTD URIフォーマットの作成

  • Nfc04.java
Ndefメッセージを書き込むをベースとしているので, まずはそちらを参照のこと.
RTD URIフォーマットのデータは, createUriRecordメソッドで作成している.
  private void writeTag(Intent intent, String text) throws IOException, FormatException {
    String action = intent.getAction();
    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
      // Ndefメッセージ生成
      NdefRecord record = createUriRecord(text);
      NdefMessage msg = new NdefMessage(new NdefRecord[] {record});
      // Ndefメッセージの書き込み
      Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
      Ndef ndef = Ndef.get(tag);
      ndef.connect();
      ndef.writeNdefMessage(msg);
      Log.v("NFC", "write " + text);
      ndef.close();
    }
  }

  // RTD URIフォーマットのNdefレコード作成
  private NdefRecord createUriRecord(String fullUri) throws UnsupportedEncodingException {
    byte[] prefix = new byte[1];
    byte[] url = null;
    // URI識別子のサーチ
    boolean found = false;
    for (int i=1; i<uriPrefixs.length; i++) {
      if (fullUri.startsWith(uriPrefixs[i])) {
        prefix[0] = (byte)i;
        // URIの残り
        url = fullUri.substring(uriPrefixs[i].length(), fullUri.length()).getBytes("UTF-8");
        found = true;
        break;
      }
    }
    if (!found) {
      prefix[0] = 0x00;
      url = fullUri.getBytes("UTF-8");
    }
    // Payloadのデータ組み立て
    byte[] payload = new byte[prefix.length + url.length];
    System.arraycopy(prefix, 0, payload, 0, prefix.length);
    System.arraycopy(url, 0, payload, prefix.length, url.length);
    return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_URI, new byte[]{}, payload);
  }

  // URI識別子のテーブル
  private static final String uriPrefixs[] = {
    "",
    "http://www.",
    "https://www.",
    "http://",
    "https://",
    "tel:",
    "mailto:",
    "ftp://anonymous:anonymous@",
    "ftp://ftp.",
    "ftps://",
    "sftp://",
    "smb://",
    "nfs://",
    "ftp://",
    "dav://",
    "news:",
    "telnet://",
    "imap:",
    "rtsp://",
    "urn:",
    "pop:",
    "sip:",
    "sips:",
    "tftp:",
    "btspp://",
    "btl2cap://",
    "btgoep://",
    "tcpobex://",
    "irdaobex://",
    "file://",
    "urn:epc:id:",
    "urn:epc:tag:",
    "urn:epc:pat:",
    "urn:epc:raw:",
    "urn:epc:",
    "urn:nfc:"};
  • 動作例
MiniTrack NXP NTAG203

                        (NFC TagInfoで確認)