使用前台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)**的设备上安装并运行应用
- 通过系统设置强制停止应用,然后卸载
- 使用以下命令一次性完成安装并启动应用(分开执行两个命令不会触发问题):
或者直接通过Android Studio重新安装并运行应用adb install app-debug.apk && adb shell am start -n "com.example.sample/com.example.sample.MainActivity"
日志现象
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
相关产品推荐
相关产品推荐

