【发布时间】:2016-10-06 06:19:59
【问题描述】:
我的应用在后台和前台使用 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 已入库或已冻结。有没有人有同样的经历?问题出在哪里?
经过一些测试,我有了新的观察结果。这仅在重新启动后发生。我虽然我的应用程序启动了两次并且存在一些线程死锁,但它没有。如果我以一些延迟(3 秒或更长时间)启动 CountDownTimer(在 onCreate 方法中调用),它会起作用并且 getDefaultAdapter 不为空。如果启动延迟太低(2 秒或更少),我在日志中发现了这条消息:“E/NFC:无法检索 NFC 服务”,然后 getDefaultAdapter 返回 null,直到我重新安装我的应用程序。
在执行 CountDownTimer 之前如此短暂的延迟(也许更好的是 Timer.schedule(..., delay, interval))是临时解决方案,但如果有人知道什么是最好的解决方案,请告诉我。
【问题讨论】:
-
你是怎么发现
NfcAdapter.getDefaultAdapter(this)返回null的?您在应用程序的哪个位置调用上述代码?mActivity是调用代码时的前台活动吗?您是否请求了 NFC 权限? -
我在 onTick 方法 (CountDownTimer) 中调用 mActivity 中的 getDefaultAdapter。在那里我设置了 ImageView 的可见性(如果 NFC 开启则可见,如果 NFC 关闭则可见)。是的,mActivity 在前台。我在清单中有 NFC 权限。
-
所以
if (mNfcAdapter != null) { mNfcAdapter.enableForegroundDispatch [...]部分是在mNfcAdapter = NfcAdapter.getDefaultAdapter(this.mActivity);之后立即调用的,还是从不同的方法调用的?会不会是您的活动在其间的某个时间点重新创建? -
都在 onCreate 方法中调用。但是 NfcAdapter.getDefaultAdapter(this.mActivity);每 5 秒在 CountDownTimer 中调用一次,并返回 null。也许它在 onCreate 中也返回 null,我不知道。我认为前台 NFC 读取停止工作,getDefaultAdapter 返回 null,但后台 NFC 读取工作。有可能吗?
-
再一次:你确定你的活动在计时器回调执行时仍在运行(即在 onResume() 和 onPause() 生命周期方法之间)?并且您的活动没有重新创建(可能使 mActivity 中的引用无效)?