【问题标题】:NFC foreground dispatch fire both onCreate and onNewIntentNFC 前台调度触发 onCreate 和 onNewIntent
【发布时间】:2017-06-28 06:45:08
【问题描述】:

我正在尝试制作可以具有以下功能的 Activity A(启动器 Activity)。

1.启动Activity A,使用nfc标签,Activity A启动后读取nfc标签。

2. Activity A在前台时检测nfc标签。

起初它可以工作一天。它会表现得像

onPause -> onNewIntent -> onResume

在应用程序单独放置一天或可能一个小时后,当我尝试转到 Activity A 并扫描 nfc 标签时,它的行为会像

onPause -> onNewIntent -> onResume -> onPause -> onCreate -> onResume。

最后 3 个步骤存在巨大问题。我认为它应该在 onNewIntent 之后的 onResume 中停止??

不管是kill app,还是从android任务列表中清除,在app卸载重装之前也不会解决问题。它不仅仅发生在一台特定的设备上,它发生在我的大多数设备上。

想知道如何解决此问题或是否有任何解决方法。非常感谢。

下面是我的代码:

活动 A

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.adapter = NfcAdapter.getDefaultAdapter(this);
    IntentFilter intentFilter = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
    techLists = new String[][] {
            new String[] {
                    NfcF.class.getName()
            }
    };
    intentFiltersArray = new IntentFilter[] { intentFilter };
    this.pendingIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, ((Object) this).getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
}

@Override
protected void onPause() {
    if (this.adapter != null) {
        this.adapter.disableForegroundDispatch(this);
    }
    super.onPause();
}

@Override
protected void onResume() {
    if (this.adapter != null) {
        this.adapter.enableForegroundDispatch(this, this.pendingIntent, intentFiltersArray, this.techLists);
    }
    super.onResume();
}

清单

<activity
    android:name=".ActivityA"
    android:launchMode="singleTask">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    <meta-data
        android:name="android.nfc.action.TECH_DISCOVERED"
        android:resource="@xml/tech" />
    <intent-filter>
        <action android:name="android.nfc.action.TECH_DISCOVERED" />
    </intent-filter>
</activity>

【问题讨论】:

  • onDestroy() 是否在 onCreate() 之前被调用?如果是这样,您可能会看到对配置更改的响应。 Android 正在杀死当前的Activity,然后创建一个新的来处理配置更改。您可以通过将android:configChanges="orientation|screenSize" 添加到清单中的&lt;activity&gt; 标记来防止这种情况发生。

标签: android android-intent nfc android-pendingintent intentfilter


【解决方案1】:

你可以这样称呼吗

super.onResume();

之前

if (this.adapter != null) {
        this.adapter.enableForegroundDispatch(this, this.pendingIntent, intentFiltersArray, this.techLists);
    } 

再检查一遍

【讨论】:

  • 现在好像没有再发生过。将继续观察行为。谢谢。
  • 我也有同样的问题!此解决方案为您解决了吗?
猜你喜欢
  • 1970-01-01
  • 2011-08-22
  • 1970-01-01
  • 2018-01-24
  • 1970-01-01
  • 2011-07-06
  • 2014-07-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多