アプリに、Android Beam(P2P接続)で機能するMIMEタイプ「application / com.sticknotes.android」のインテントフィルターがすでにある場合は、同じMIMEタイプのNDEFメッセージを含むタグでも機能します。Android Beamとタグ検出はどちらもACTION_NDEF_DISCOVERED
、受信/読み取りデバイスでインテントを生成します。
このようなNDEFメッセージをMIFAREClassic1Kタグに書き込むために、それを実行する簡単なアプリを作成できます。このアプリのマニフェストファイルに次のように入力します。
<activity>
...
<intent-filter>
<action android:name="android.nfc.action.TECH_DISCOVERED"/>
</intent-filter>
<meta-data android:name="android.nfc.action.TECH_DISCOVERED"
android:resource="@xml/nfc_tech_filter" />
...
</activity>
そして、プロジェクトのres/xml
フォルダにnfc_tech_filter.xml
次の内容のファイルを置きます。
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<tech-list>
<tech>android.nfc.tech.MifareClassic</tech>
</tech-list>
</resources>
アプリのActivity
プット:
onCreate(Bundle savedInstanceState) {
// put code here to set up your app
...
// create NDEF message
String mime = "application/com.sticknotes.android";
byte[] payload = ... ; // put your payload here
NdefRecord record = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, mime.toBytes(), null, payload);
NdefMessage ndef = new NdefMessage(new NdefRecord[] {ndef});
// write NDEF message
Intent intent = getIntent();
if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction()) {
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
NdefFormatable nf = NdefFormatable.get(tag);
if (nf != null) {
// tag not yet formatted with NDEF
try {
nf.connect();
nf.format(ndef);
nf.close();
} catch (IOException e) {
// tag communication error occurred
}
} else {
Ndef n = Ndef.get(tag);
if (n != null && n.isWritable() ) {
// can write NDEF
try {
n.connect();
n.writeNdefMessage(ndef);
n.close();
} catch (IOException e) {
// tag communication error occurred
}
}
}
}
}
これにより、NDEFメッセージがフォーマットされていない(空白の)MIFAREクラシックタグに書き込まれるか、すでにNDEFでフォーマットされているタグが上書きされます。MIFAREクラシック以外のタグタイプを記述したい場合は、nfc_tech_filter.xml
それに応じて調整してください。