我开发了一个可检测NFC卡的Android应用程序,然后与它打开IsoDep连接以发送APDU并获取响应。当应用程序检测到NFC卡时,它打开了一个工作会话,我创建了一个thread
,每个500 ms
检查isoDep连接,如果连接丢失,则应用程序关闭工作会话(停止合并,删除卡数据.. )。
我的应用程序是设备所有者,并且已被锁定,并且它仅包含一个活动,该活动启动一个webview来为用户界面打开html代码。
在MainActivity中,我在super.onPause()之前在onPause()中停止池化,并在super.onResume()之后在onResume()中重新启动池。
另外,我总是在onResume()中调用NfcAdapter.enableReaderMode()
,在onPause()中调用NfcAdapter.disableReaderMode
。
//enable nfc dispatch
Bundle options = new Bundle();
options.putInt(NfcAdapter.EXTRA_READER_PRESENCE_CHECK_DELAY, 50);
NfcManager manager = (NfcManager) activity.
getApplicationContext().getSystemService(Context.NFC_SERVICE);
if(manager == null) {
return;
}
NfcAdapter nfcAdapter = manager.getDefaultAdapter();
if(nfcAdapter == null) {
return;
}
try {
nfcAdapter.enableReaderMode(activity,
new NfcAdapter.ReaderCallback() {
@Override
public void onTagDiscovered(final Tag tag) {
cardDetected(tag);
}
},
NfcAdapter.FLAG_READER_NFC_A | NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK |
NfcAdapter.FLAG_READER_NO_PLATFORM_SOUNDS,
options);
} catch (Exception e) {
}
//disable nfc dispatch
NfcManager manager = (NfcManager)activity.getApplicationContext().getSystemService(Context.NFC_SERVICE);
if(manager == null) {
return;
}
NfcAdapter nfcAdapter = manager.getDefaultAdapter();
if(nfcAdapter == null) {
return;
}
try {
nfcAdapter.disableReaderMode(activity);
} catch (Exception e) {
}
我使用Samsung Xcover4 Android 8测试该应用程序。我的问题是某个时候调用了onResume时,我在 logcat 中看到了DeadObjectException:
E/NFC: NFC service dead - attempting to recover
android.os.DeadObjectException
at android.os.BinderProxy.transactNative(Native Method)
at android.os.BinderProxy.transact(Binder.java:777)
at android.nfc.INfcAdapter$Stub$Proxy.setAppCallback(INfcAdapter.java:1026)
at android.nfc.NfcActivityManager.requestNfcServiceCallback(NfcActivityMan ager.java:494)
at android.nfc.NfcActivityManager.onActivityResumed(NfcActivityManager.java:674)
at android.app.Application.dispatchActivityResumed(Application.java:240)
at android.app.Activity.onResume(Activity.java:1369)
at android.support.v4.app.FragmentActivity.onResume(FragmentActivity.java:514)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1363)
at android.app.Activity.performResume(Activity.java:7432)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3780)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3845)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1773)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:7000)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:441)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
当发生这种情况时,永远不会检测到卡,我必须重新启动NFC或应用程序才能检测到卡。