NFC和MIME类型区分大小写问题

4

我正在尝试使用 NFC 的基础版本,但是我发现 MIME 类型是大小写敏感的。我的应用程序的包名有一个大写字母。

包名:com.example.Main_Activity

<intent-filter>
  <action android:name="android.nfc.action.NDEF_DISCOVERED"/>
  <category android:name="android.intent.category.DEFAULT"/>
  <data android:mimeType="application/com.example.Main_Activity"/>
</intent-filter>

有什么解决办法吗?

在这个上下文中,“NFC”是什么?实际的物理/协议[近场通信]还是某种编程事物的名称,比如Android API的名称? - Peter Mortensen
2个回答

2

MIME类型是根据RFC大小写不敏感的。然而,Android的intent过滤器匹配是区分大小写的。为了解决这个问题,您应该始终只使用小写 MIME 类型。

特别是对于Android NFC API的MIME类型记录帮助方法,MIME类型将自动转换为仅小写字母。因此,使用混合大小写的类型名称调用NdefRecord.createMime()方法将始终导致创建仅小写 MIME 类型名称。例如:

NdefRecord r1 = NdefRecord.createMime("text/ThisIsMyMIMEType", ...);
NdefRecord r2 = NdefRecord.createMime("text/tHISiSmYmimetYPE", ...);
NdefRecord r3 = NdefRecord.createMime("text/THISISMYMIMETYPE", ...);
NdefRecord r4 = NdefRecord.createMime("text/thisismymimetype", ...);

所有这些操作都将导致创建相同的MIME类型记录类型:

+----------------------------------------------------------+
| MIME:text/thisismymimetype | ...                         |
+----------------------------------------------------------+

所以你的意图过滤器也需要全部是小写字母:

<intent-filter>
    <action android:name="android.nfc.action.NDEF_DISCOVERED" />
    <category android:name="android.intent.category.DEFAULT" />
    <data android:mimeType="text/thisismymimetype" />
</intent-filter>

2

我终于明白了。即使我的包名中有大写字母,你在代码和意图过滤器中必须使用小写字母编写你的MIME类型。

我知道实际上它们不是同一个包。然而,在NFC中的MIME类型仍会识别你的应用程序。只需确保在创建应用程序记录时编写正确的包名。如果你注意到,我不得不使用正确的包名,其中包括大写字母。否则,你的应用程序将无法找到。

public NdefMessage createNdefMessage(NfcEvent event) {
    String text = ("Beam me up, Android!\n\n" +
                   "Beam Time: " + System.currentTimeMillis());
    NdefMessage msg = new NdefMessage(
            new NdefRecord[] { NdefRecord.createMime(
                    "application/com.example.main_activity", text.getBytes())
     /**
      * The Android Application Record (AAR) is commented out. When
      * a device receives a push with an AAR in it, the application
      * specified in the AAR is guaranteed to run.
      *
      * The AAR overrides the tag dispatch system. You can add it
      * back in to guarantee that this activity starts when
      * receiving a beamed message. For now, this code uses
      * the tag dispatch system.
      */
      ,NdefRecord.createApplicationRecord("com.example.Main_Activity")
    });
    return msg;
}

<intent-filter>
    <action android:name="android.nfc.action.NDEF_DISCOVERED"/>
    <category android:name="android.intent.category.DEFAULT"/>
    <data android:mimeType="application/com.example.main_activity"/>
</intent-filter>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接