请求NFC访问权限 Link to heading
在AndroidManifest.xml文件中添加以下内容。
💡/app/src/main/AndroidManifest.xml
- 声明权限
<uses-permission android:name="android.permission.NFC" />
- 声明是否使用NFC功能
💡必须的话required设为true,否则设为false
<uses-feature android:name="android.hardware.nfc" android:required="false" />
过滤NFC Intent Link to heading
有三种Intent,分别是ACTION_NDEF_DISCOVERED,ACTION_TECH_DISCOVERED和ACTION_TAG_DISCOVERED。
💡这里咱们以ACTION_TAG_DISCOVERED为例。
在AndroidManifest.xml文件相应的Activity代码段中添加过滤器。
<activity android:name=".NfcActivity"
android:exported="true">
<intent-filter>
<action android:name="android.nfc.action.TAG_DISCOVERED"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
从Intent中获取NFC标签信息 Link to heading
在相应的Activity文件中重载onNewIntent函数。
💡/app/src/main/java/tokyo/randx/portfolio/android/NfcActivity.kt
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
if (NfcAdapter.ACTION_TAG_DISCOVERED == intent?.action) {
val tag = intent.getParcelableExtra<Parcelable>(NfcAdapter.EXTRA_TAG) as Tag?
val techList = tag!!.techList
val tagIdBytes = tag.id
}
}
使用前台调度系统 Link to heading
在相应的Activity文件中重载onResume()和onPause()函数。
💡/app/src/main/java/tokyo/randx/portfolio/android/NfcActivity.kt
override fun onResume() {
super.onResume()
// Enable Foreground Dispatch
nfcAdapter.enableForegroundDispatch(this, pendingIntent, null, null)
}
override fun onPause() {
super.onPause()
// Disable Foreground Dispatch
nfcAdapter.disableForegroundDispatch(this)
}