5月 122011
			
		
Nexus SのNFCでFelicaのIDを読む – 橋本詳解の時に、Android 2.3 GingerBread NFCをやってみる – TOPGATE Google関連技術サイトのTagWrapper.javaを使わせてもらってたんだけど先日のNexus Sのandroid2.3.4へのアップデートで動かなくなったので少しやり方変えた。
TagWrapper.javaの中でやってる事を参考にさせてもらった。
ただFelicaのユニークなIDだけが必要だったらこれでいい
(先に橋本詳解の方に書いたManifestとかguavaとかを設定しておく必要はある)
import java.lang.reflect.*;たくさんのimportが必要。
import java.util.*;
import com.google.common.primitives.UnsignedBytes;
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);
        resolveIntent(this.getIntent());
    }
    void resolveIntent(Intent intent) {
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
            try{
                Parcelable tag = intent.getParcelableExtra("android.nfc.extra.TAG");
                Field f = tag.getClass().getDeclaredField("mId");
                f.setAccessible(true);
                byte[] mId = (byte[]) f.get(tag);
                StringBuilder sb = new StringBuilder();
                for (byte id : mId) {
                    String hexString = Integer.toHexString(UnsignedBytes.toInt(id));
                    if (hexString.length() == 1) sb.append("0");
                    sb.append(hexString);
                }
                String id = sb.toString();
                Log.v("TAG", id);
            }
            catch(Exception e){
                e.printStackTrace();
            }
        }
    }