Nexus SのNFCでFelicaのIDを読む

http://code.google.com/p/guava-libraries/ から guava-r09.jar を手に入れて、Androidプロジェクトにlibsディレクトリを作ってその中に入れる。
プロジェクトのbuild pathにguava-r09.jarを追加する。


AndroidManifest.xmlにpermissionを書いておく

<uses-permission android:name="android.permission.NFC" />
<uses-feature android:name="android.hardware.nfc" android:required="true" />

適当なActivityの中にintent filterも書いておく

<intent-filter>
  <action android:name="android.nfc.action.TAG_DISCOVERED" />
  <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

これで、FelicaやおさいふケータイやSFCの学生証をNexus Sに接触させると、TAG_DISCOVEREDのintentが発生して、それで自分のプログラムが起動するようになる。


発生したintentを受け取って、NFCタグからのintentか判別してtagのidを取り出すまで。

import jp.co.topgate.android.nfc.TagWrapper;
import android.app.Activity;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.*;
   public void onCreate(Bundle savedInstanceState) {        
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Intent intent = this.getIntent();

        String action = intent.getAction();
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {
            try{
                Parcelable tag = intent.getParcelableExtra("android.nfc.extra.TAG");
                TagWrapper tw = new TagWrapper(tag);
                String id = tw.getHexIDString();
                Log.v("NFC TAG ID", id);
            }
            catch(Exception e){
                Log.e("NFC", e.toString());
            }
        }

Android 2.3 GingerBread NFCをやってみる - TOPGATE Google関連技術サイトにあるTagWrapper.javaを使わせていただいた。Felicaとそれ以外を識別できたりとか超便利!!!