在NFC标签扫描期间,在onNewIntent()方法中,intent.getAction()为空。

4

这是我第一次使用NFC标签技术。我已经在Manifest中声明了NFC扫描活动,如下所示:

    <activity
        android:name=".main.NFCScanActivity"
        android:theme="@android:style/Theme.Holo.Light"
        android:launchMode="singleTop"
        android:exported="true">
        <intent-filter>
            <action android:name="android.nfc.action.NDEF_DISCOVERED" />
            <category android:name="android.intent.category.DEFAULT" />
            <data android:mimeType="text/plain" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.nfc.action.TECH_DISCOVERED" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
        <meta-data android:name="android.nfc.action.TECH_DISCOVERED"
            android:resource="@xml/nfc_tech_filter" />
    </activity>

以下是nfc_tech_filter.xml文件:

<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<tech-list>
    <tech>android.nfc.tech.IsoDep</tech>
    <tech>android.nfc.tech.NfcA</tech>
    <tech>android.nfc.tech.NfcB</tech>
    <tech>android.nfc.tech.NfcF</tech>
    <tech>android.nfc.tech.NfcV</tech>
    <tech>android.nfc.tech.Ndef</tech>
    <tech>android.nfc.tech.NdefFormatable</tech>
    <tech>android.nfc.tech.MifareClassic</tech>
    <tech>android.nfc.tech.MifareUltralight</tech>
</tech-list>

每当我扫描标签时,都会调用onNewIntent(),但是当我尝试在onNewIntent中调用intent.getAction()时,值始终为null。
@Override
protected void onNewIntent(Intent intent) {
    handleIntent(intent);
}
private void handleIntent(Intent intent) {
    String action = intent.getAction(); // action here is null
}

你能否更新问题并附上负责获取意图的代码? - Mustafa Dakhel
这是在应用程序已经在前台运行还是您正在尝试在扫描NFC标签时启动应用程序? - Andrew
@Andrew 应用程序在前台。 - Bhargav Mehta
2个回答

6

当您想要在应用程序处于前台时处理NFC时,使用两个前台NFC API中的一个是更常见的做法。通常,清单中的NFC条目仅用于通过NFC触发器启动您的应用程序。

enableReaderMode是两个前台NFC Api中更好且更新的API,或者还有旧的enableForegroundDispatch

使用enableReaderMode的示例

如果使用清单条目处理NFC,则应该在onCreate中处理您的ActivitygetIntent返回值,以查看是否创建了来自NFC触发器的Intent。


enableReaderMode 工作得非常完美。谢谢! - Bhargav Mehta
请将答案标记为已接受,因为它解决了您的问题。谢谢。 - Andrew

6
确保NFC的挂起意图标志设置为可变。
PendingIntent.getActivity(
   activity, 
   KEY_PENDING_INTENT_REQUEST_CODE,  
   Intent(
      activity,
      activity.javaClass)
        .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 
   PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE
)
    

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