点击 NFC 标签时创建的新程序实例

New program instance created when NFC Tag tapped

我的 Android 应用程序正在对事件“NDEF_DISCOVERED”使用意图过滤器,如果它包含某个 URL 则打开它。 它工作正常,但我注意到,如果我将我的应用程序置于后台并点击 NFC 标签,程序的一个新实例将启动。如果我这样做几次,我就会创建多个应用程序实例。这给我带来了一些问题,所以我想找到一个解决方案,以便只打开一个实例。

旁注:当我的程序在前台运行时,我在 onResume 中使用 enableForegroundDispatch() 并在 onPause 中使用 disableForegroundDispatch() 。它工作正常。

当我的程序在后台并且当我点击一个 NFC 标签时,系统是否可以检测到该程序已经启动并将其置于前台而不是启动一个新实例?

作为比较,如果我将我的程序置于后台,转到程序列表并单击我的程序,Android 检测到该程序已经打开并在不创建新程序的情况下恢复它实例(在这种情况下不会调用 MainActivity 的 onCreate())。为什么我们对 NFC 事件没有相同的行为,是否有可能有相同的行为?

我已经阅读了这个帖子 ( ),这是同一个问题,但它没有帮助我找到解决方案。

我已添加:

android:launchMode="singleTask"

here 所示,它确实有效。

如文档所述:(来源 https://developer.android.com/guide/components/activities/tasks-and-back-stack

"singleTask" :

The system creates a new task and instantiates the activity at the root of the new task. However, if an instance of the activity already exists in a separate task, the system routes the intent to the existing instance through a call to its onNewIntent() method, rather than creating a new instance. Only one instance of the activity can exist at a time.