我用一些额外内容开始了一个 Intent,并阅读了 Activity 的 onCreate
中传递的额外内容。
class MyActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val extras: Bundle? = intent.extras // <-- crash
val someInt = extras?.getInt(EXTRA_SOME_INT, -1) ?: -1
// ...
}
companion object {
const val EXTRA_SOME_INT = "someInt"
fun createIntent(context: Context, someInt: Int) =
Intent(context, MyActivity::class.java).apply {
putExtra(EXTRA_SOME_INT, someInt)
}
}
}
// Activity started like this:
fun startMyActivity(context: Context) {
context.startActivity(MyActivity.createIntent(context, 1234))
}
这工作正常,但是,在生产中,标记的行有时会导致应用程序在 getExtras()
时崩溃。叫做。根据文档,它可以为空,但不应引发异常。崩溃日志并不总是相同,但要么发生在
BaseBundle
中。 :java.lang.NullPointerException
Attempt to invoke virtual method 'int android.os.Parcel.dataSize()' on a null object reference
BaseBundle.java line 164 in android.os.BaseBundle.<init>()
Bundle.java line 106 in android.os.Bundle.<init>()
Intent.java line 6580 in android.content.Intent.getExtras()
...或者发生这种情况:java.lang.IllegalArgumentException
Duplicate key in ArrayMap:
BaseBundle.java line 126 in android.os.BaseBundle.<init>()
Bundle.java line 102 in android.os.Bundle.<init>()
Intent.java line 5756 in android.content.Intent.getExtras()
崩溃仅发生在 Android 5、6 或 7 上。我还没有找到在我自己的设备上重现它的方法。我做错了什么,或者避免这种崩溃的最佳方法是什么?如果没有额外的 bundle ,我将无法显示我的 Activity 。
最佳答案
这是 AOSP 中的一个错误,它是 fixed。在 Android 7 之后。这是提交消息中的原因:
Fix for race in writeToParcel and unparcel
Don't access the parcelled data while it might be recycled by another thread.
Also make a local reference of mMap, which could be modified by another thread.
关于android - getIntent().getExtras() 有时会在 Activity 中崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63225930/