我尝试创建一个应用来从其他设备读取nfc消息:
AndroidManifest.xml
...
<activity android:name=".NFCActivity">
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED"/>
<action android:name="android.nfc.action.TECH_DISCOVERED" />
<action android:name="android.nfc.action.TAG_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
<meta-data android:name="android.nfc.action.TECH_DISCOVERED" android:resource="@xml/tech_list" />
</application>
<uses-sdk android:minSdkVersion="10"/>
<uses-feature android:name="android.hardware.nfc" android:required="true" />
<uses-permission android:name="android.permission.NFC" />
我的活动:
class NFCActivity : AppCompatActivity() {
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
if (NfcAdapter.ACTION_NDEF_DISCOVERED == intent.action) {
intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES)?.also { rawMessages ->
val messages: List<NdefMessage> = rawMessages.map { it as NdefMessage }
println(String(messages[0].records[0].payload));
}
}
val tag: Tag? = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG)
println(tag)
}
}
我的技术列表:
<?xml version="1.0" encoding="utf-8"?>
<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>
</resources>
[从两个不同的设备发送URL时,不会调用该活动。有没有人想办法解决?
您可以在此处找到来源:https://github.com/enthusiasmus/nfc
提前感谢!
[使用通过Intents获取NFC数据的旧样式时,NFC数据有两个可能的入口点。
1)您的活动已经在运行,并且如果您有enableForegroundDispatch
https://developer.android.com/guide/topics/connectivity/nfc/advanced-nfc#foreground-dispatch,那么系统生成的Intent将传递到onNewIntent
,但是由于您的NFCActivity未运行,并且您没有enableForegroundDispatch
,因此它不会传递给onNewIntent
2)您已设置NFC Intent筛选器,并且您的应用未运行,然后首次启动活动,然后您将在onCreate
中而不在onNewIntent
中处理Intent>
这是因为onNewIntent
的文档说
https://developer.android.com/reference/android/app/Activity#onNewIntent(android.content.Intent)
当在活动堆栈顶部重新启动活动而不是启动活动的新实例时,将在现有实例上使用用于重新启动它的Intent调用onNewIntent()。-未调用启动的由于您的活动不是
RE
onNewIntent
。我见过的大多数应用程序都将Intent处理移至单独的方法例如readFromIntent
然后,当由NFC过滤器启动应用程序时,从onCreate
调用readFromIntent
要么当应用程序已经在运行并且onNewIntent
导致系统将NFC意图发送到已经运行的应用程序时,从readFromIntent
调用enableForegroundDispatch
。另外,您可能会发现Intent不会以NDEF_DISCOVERED的形式出现,因为您的NFC过滤器中没有设置数据类型
例如
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="*.*" />
</intent-filter>
从https://developer.android.com/guide/topics/connectivity/nfc/nfc#ndef-disc开始,但是*。*将得到所有类型,如果需要,可以稍后将范围缩小。