1

我的 Android NFC 应用程序在完成读取智能卡后,会再次显示相同的 NFC 标签信息,并由操作系统再次启动。事实上,如果你不移动手机,它就会进入一个永久循环。正在读取的数据量确实需要一两秒钟,所以最后它会重新开始。(这在我的 Galaxy S2 Gingerbread 和我的 ICS 上的 S3 上相当常见)

当 NFC 源(智能卡)没有改变并且没有从手机上移开时,如何阻止它重复?

我的活动有一个意图过滤器:

            <intent-filter >
                <action android:name="android.nfc.action.TECH_DISCOVERED" />
                <category android:name="android.intent.category.DEFAULT" />
                <action android:name="android.nfc.action.TAG_DISCOVERED" />
            </intent-filter>
            <meta-data
                android:name="android.nfc.action.TECH_DISCOVERED"
                android:resource="@xml/filter_nfc" />

有一份技术清单

 <tech-list>
     <tech>android.nfc.tech.IsoDep</tech>
 </tech-list>

源代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
    resolveIntent(getIntent());
}

@Override
public void onNewIntent(Intent intent) {
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
}

private void resolveIntent(Intent intent) {
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    final String action = intent.getAction();
    if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
                 || NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {
        ....work
        handled = true;
    }
    if (!handled) {
        Log.e(tag, "Unknown intent " + intent);
        finish();
        return;
    }
}
4

2 回答 2

0

The only way I could solve it was to place a time check - inside the onCreate (setContentView line and resolveIntent line) and also inside the onNewIntent function.

This did not stop Android from trying to call the app again to process the NFC but my app did not do anything if it was called within 2 seconds from the last successful NFC read.

Maybe not the cleanest way but it is effective against the looping problem and passes all the tests on different devices.

于 2012-08-01T15:03:12.813 回答
0

这是不正常的,但我也看到过类似的行为。我尝试的是启用 NFC 前台调度。这使您的应用可以完全控制传入的 NFC 意图。然后根据标签的 ID(或者可能是自上次 NFC 事件以来经过的时间),您可以决定忽略标签。

@Override
protected void onResume() {
  ...
  ForegroundDispatch.setupForegroundDispatch(this);
}

@Override
protected void onPause() {
  ...
  ForegroundDispatch.stopForegroundDispatch(this);
};

@Override
public void onNewIntent(Intent intent) {
  ... // check for the tag's ID or elapsed time to determine how to react
}
于 2012-08-03T22:20:00.700 回答