当通过 Mifare 卡使用 NFC 服务时,如何使用 Intent Filter 直接打开应用程序?我知道您可以使用 Intent 过滤器,直接使用特定的 mimeType 来进行 P2P 连接,例如
<data android:mimeType="application/com.sticknotes.android"/>
我只是不确定如何设置 Mifare1K 的扇区来完成同样的事情。有人对如何做到这一点有任何想法吗?或者我仅限于弹出应用程序选择器?
我想我可以创建一个完全独立的 Activity 来处理无源标签与有源设备,但是有没有办法在一个 Activity 中处理这一切?
最佳答案
如果您的应用程序已经具有适用于 Android Beam(P2P 连接)的 MIME 类型“application/com.sticknotes.android”的 Intent 过滤器,那么它也适用于包含具有相同 MIME 的 NDEF 消息的标签类型。 Android Beam 和标签发现都会在接收/读取设备中生成 ACTION_NDEF_DISCOVERED
Intent。
要将此类 NDEF 消息写入 MIFARE Classic 1K 标签,您可以创建一个简单的应用程序来为您执行此操作。在此应用程序的 list 文件中放入:
<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 Classic 标签,或覆盖已使用 NDEF 格式化的标签。如果您想编写除 MIFARE Classic 之外的其他标签类型,请相应地调整 nfc_tech_filter.xml
。
关于android - 如何为 Mifare 卡创建特定于应用程序的 Intent 过滤器? (安卓),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9823925/