如何为Mifare卡创建特定于应用程序的intent过滤器? (机器人)

时间:2012-03-22 14:08:23

标签: android android-intent mime-types nfc mifare

将NFC服务与Mifare卡一起使用时,如何使用意图过滤器直接打开应用程序?我知道您可以使用特定mimeType的intent过滤器直接用于P2P连接,如

<data android:mimeType="application/com.sticknotes.android"/>

我只是不确定如何设置Mifare1K的扇区来做同样的事情。有人对如何做到这一点有任何想法吗?或者我只是限制应用程序选择器弹出窗口?

我想我可以创建一个完全独立的活动来处理被动标签与活动设备,但有没有办法在一个活动中处理这一切?

1 个答案:

答案 0 :(得分:2)

如果您的应用已经具有适用于Android Beam(P2P连接)的MIME类型“application / com.sticknotes.android”的intent过滤器,那么它也可以使用包含具有相同MIME的NDEF消息的标记类型。 Android Beam和标记发现都会在接收/读取设备中生成ACTION_NDEF_DISCOVERED意图。

要将这样的NDEF消息写入MIFARE Classic 1K标记,您可以创建一个简单的应用程序来为您执行此操作。在这个应用程序的清单文件中:

<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