You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用前台NFC调度时Android Activity.onCreate被调用两次问题

问题:前台NFC调度场景下,强制停止卸载后重新安装启动,Activity.onCreate()被调用两次

当应用使用前台NFC调度,且在强制停止后卸载再重新安装启动时,会出现Activity.onCreate()被调用两次的异常情况,具体细节如下:

复现步骤

  • 创建如下Activity代码:
package com.example.sample

class MainActivity : AppCompatActivity() {
    private val nfcTechList: Array<Array<String>> = arrayOf(arrayOf(IsoDep::class.java.name))
    private val nfcIntentFilters: Array<IntentFilter> = arrayOf(IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED, "*/*"))

    private lateinit var nfcAdapter: NfcAdapter
    private lateinit var pendingIntent: PendingIntent

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.d("SAMPLE_TAG", "onCreate")
        setContentView(R.layout.activity_main)

        nfcAdapter = NfcAdapter.getDefaultAdapter(applicationContext)
        val nfcIntent = Intent(this, javaClass).apply {
            addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
        }
        pendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            PendingIntent.getActivity(this, 0, nfcIntent, PendingIntent.FLAG_MUTABLE)
        } else {
            PendingIntent.getActivity(this, 0, nfcIntent, 0)
        }
    }

    override fun onResume() {
        super.onResume()
        Log.d("SAMPLE_TAG", "onResume")
        nfcAdapter.enableForegroundDispatch(this, pendingIntent, nfcIntentFilters, nfcTechList)
    }

    override fun onPause() {
        super.onPause()
        Log.d("SAMPLE_TAG", "onPause")
        nfcAdapter.disableForegroundDispatch(this)
    }
}
  • 在**Android 12及以上(targetSdk=33)**的设备上安装并运行应用
  • 通过系统设置强制停止应用,然后卸载
  • 使用以下命令一次性完成安装并启动应用(分开执行两个命令不会触发问题):
    adb install app-debug.apk && adb shell am start -n "com.example.sample/com.example.sample.MainActivity"
    
    或者直接通过Android Studio重新安装并运行应用

日志现象

Logcat中可以看到onCreate()被调用两次,生命周期流程异常:

14:20:55.419 22851 22851 D SAMPLE_TAG: onCreate
14:20:55.542 22851 22851 D SAMPLE_TAG: onResume
14:20:55.575 22851 22851 D SAMPLE_TAG: onPause
14:20:55.612 22851 22851 D SAMPLE_TAG: onCreate
14:20:55.640 22851 22851 D SAMPLE_TAG: onResume

预期与实际情况

  • 预期:无论以何种方式启动应用,Activity.onCreate()都应仅被调用一次,符合Activity生命周期规范(注:使用的前台NFC调度代码完全来自官方文档)
  • 实际:onCreate()及后续的onResume()被调用两次,违背正常生命周期流程

内容的提问来源于stack exchange,提问作者Xeniale

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 10:12:16