こんにちわ、
九州GDGの松岡です。
NfcAdapterを使用することで可能です
まずonCreateでmAdapterを作成します
public void onCreate(Bundle savedInstanceState){
mAdapter = NfcAdapter.getDefaultAdapter(this);
boolean isNfcExist =
getPackageManager().hasSystemFeature(PackageManager.FEATURE_NFC);
if(mAdapter!=null && mAdapter.isEnabled() && isNfcExist){
mPendingIntent = PendingIntent.getActivity(this, 0,
new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
try {
ndef.addDataType("*/*");
} catch (MalformedMimeTypeException e) {
throw new RuntimeException("fail", e);
}
mFilters = new IntentFilter[] {
ndef,
};
mTechLists = new String[][] {
new String[]{NfcF.class.getName()}//その他必要なTechListsを追加
};
}
}
次に、onResume()でフォアグラウンドディスパッチを有効にします。
これにより、画面が開いている間NFCのIntentをフォアグラウンドのアクティビ
ティが処理するようになります。
(アプリが再起動しなくなります)
@Override
public void onResume() {
super.onResume();
if (mAdapter != null && mAdapter.isEnabled() ){
if(getPackageManager().hasSystemFeature(PackageManager.FEATURE_NFC)){
mAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters,
mTechLists);
}
}
}
新しいカードを認識した場合はonNewIntent(Intent intentが呼ばれます
@Override
public void onNewIntent(Intent intent) {
//いろんな処理
}
画面が消えるときはフォアグラウンドディスパッチを無効にするのを忘れずに
@Override
public void onPause() {
super.onPause();
if (mAdapter != null) mAdapter.disableForegroundDispatch(this);
}
soundFireでNFCを登録するときに使用しているテクニックです
と言うステマ
https://play.google.com/store/apps/details?id=org.firespeed.nfcboot