I have created this activity to create my own type of NFC tag
public class WriteTag extends Activity {
Tag tag;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.write_tag);
}
public void onResume()
{
super.onResume();
Intent intent = getIntent();
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
try {
write("my/type", "this is payload text", tag);
finish();
}
catch(Exception e)
{
}
}
}
private NdefRecord createRecord(String mimeType, String text) throws UnsupportedEncodingException {
NdefRecord recordNFC = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, "my/type".getBytes(Charset.forName("US-ASCII")), new byte[0], text.getBytes(Charset.forName("US-ASCII")));
return recordNFC;
}
private void write(String mimeType, String text, Tag tag) throws IOException, FormatException {
NdefRecord[] records = { createRecord(mimeType, text) };
NdefMessage message = new NdefMessage(records);
Ndef ndef = Ndef.get(tag);
ndef.connect();
ndef.writeNdefMessage(message);
ndef.close();
}
}
And I use this filter in manifest to trigger it to start the write action
otherwise I don't know how to get the tag instance
<activity android:name=".WriteTag">
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="my/tag" />
</intent-filter>
</activity>
But there is a big problem, I must use another app to write the my/type into the NFC tag first, otherwise my app cannot recognize the tag.
How to force the app to write into any NFC tag? and why other app can let user: 1 tap button, 2 wait the tag approach, 3 write into tag?