我的应用程序在后台和前台使用 NFC 读取。对于用户信息,我在活动中使用 CountDownTimer(120 * 1000, 5 * 1000) 和方法 onTick(long l) 每 5 秒检查一次 NFC 状态。有时(在 Android 4.2.2 上,我的客户说,这从来没有发生在我身上)NfcAdapter.getDefaultAdapter(BaseActivity.this) 返回 null,但后台和前台 NFC 读取仍然有效!关闭和打开没有帮助。重新安装有帮助。
通过清单读取 BG:
<activity
android:name=".activity.NfcReaderActivity"
android:launchMode="singleTask"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="http" />
<data android:scheme="https" />
</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>
FG 通过意图读取:
IntentFilter ndef = new IntentFilter();
ndef.addAction(NfcAdapter.ACTION_TECH_DISCOVERED);
ndef.addCategory(Intent.CATEGORY_DEFAULT);
try {
ndef.addDataType("*/*");
} catch (IntentFilter.MalformedMimeTypeException e) {
throw new RuntimeException("fail", e);
}
mNfcAdapter = NfcAdapter.getDefaultAdapter(this.mActivity);
mNfcPendingIntent = PendingIntent.getActivity(
this.mActivity, 0,
new Intent(this.mActivity, this.mActivity.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),
0
);
mNfcFilters = new IntentFilter[] {
ndef
};
mNfcTechLists = new String[][] { new String[] {
// White solid cards
NfcA.class.getName()
} };
if (mNfcAdapter != null) {
mNfcAdapter.enableForegroundDispatch(
mActivity,
mNfcPendingIntent,
mNfcFilters,
mNfcTechLists
);
}
NfcAdapter 似乎有库存或冻结。有人有同样的经历吗?问题可能出在哪里?
经过一些测试我有了新的观察结果。仅在重新启动后才会发生这种情况。我虽然我的应用程序启动了两次并且存在一些线程死锁,但事实并非如此。如果我启动 CountDownTimer (在 onCreate 方法中调用)有一些延迟(3 秒或更多秒),它就会工作并且 getDefaultAdapter 不为空。如果启动延迟太低(2 秒或更少),我在日志中发现此消息:“E/NFC:无法检索 NFC 服务”,然后 getDefaultAdapter 返回 null,直到我重新安装我的应用程序。
在执行 CountDownTimer 之前的短暂延迟(也许更好的是 Timer.schedule(...,delay,interval))是临时解决方案,但如果有人知道最好的解决方案是什么,请告诉我。