PreferenceFragmentCompat 在测试时有效,但在已发布的应用程序上崩溃

PreferenceFragmentCompat works while testing but crashes on published app

我 运行 遇到 PreferenceFragmentCompat 的一个非常奇怪的错误。我使用指南 here 将我的偏好分成多个屏幕。这在使用 AVD 测试和使用我连接到 Android Studio 的设备进行测试时按预期工作。但是,当我将应用程序发布到 Play 商店并 运行 发布的版本时,每次我尝试单击多个设置之一时它都会崩溃。我已经确认 Android 8 和 10 都崩溃了。我不知道为什么它在测试时按预期工作,但在已发布的版本中却崩溃了?我正在发布到一个封闭的 alpha 轨道。我试过在崩溃时使用“发送反馈”选项来查看崩溃报告,但它在 Play 控制台中不可用,所以我无法追踪发生了什么。下面是代码:

build.gradle (Module: app)
...
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
implementation 'androidx.preference:preference:1.1.1'
...
MainActivity.kt

class MainActivity : AppCompatActivity() {
    private lateinit var settingsButton: ImageButton

    override fun onCreate(savedInstanceState: Bundle?) {
        ...
        settingsButton = findViewById(R.id.settingsButtonMain)
        settingsButton.setOnClickListener {
            settingsClicked()
        }
        ...
    }

    private fun settingsClicked() {
        val settingsIntent = Intent(this, SettingsActivity::class.java)
        startActivity(settingsIntent)
    }
}
SettingsActivity.kt

class SettingsActivity : AppCompatActivity(), PreferenceFragmentCompat.OnPreferenceStartFragmentCallback {
    override fun onCreate(savedInstanceState: Bundle?) {
        ...
        supportFragmentManager.beginTransaction().replace(R.id.settings, SettingsFragment(this)).commit()
        supportFragmentManager.addOnBackStackChangedListener {
            if(supportFragmentManager.backStackEntryCount == 0) {
                title = "App Settings"
            }
        }
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        ...
    }

    class SettingsFragment(cont: Context) : PreferenceFragmentCompat() {
        private var context1: Context = cont

        override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
            setPreferencesFromResource(R.xml.root_preferences, rootKey)
        }
    }

    class Screen1PreferencesFragment : PreferenceFragmentCompat() {
        override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
            setPreferencesFromResource(R.xml.screen1_preferences, null)
        }
    }

    class Screen2PreferencesFragment : PreferenceFragmentCompat() {
        override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
            setPreferencesFromResource(R.xml.screen2_preferences, null)
        }
    }

    override fun onPreferenceStartFragment(caller: PreferenceFragmentCompat?, pref: Preference): Boolean {
        val args: Bundle = pref.extras
        val fragment: Fragment = supportFragmentManager.fragmentFactory.instantiate(classLoader, pref.fragment)
        fragment.arguments = args
        fragment.setTargetFragment(caller, 0)
        supportFragmentManager.beginTransaction().replace(R.id.settings, fragment).addToBackStack(null).commit()

        return true
    }

    override fun onSupportNavigateUp(): Boolean {
        if(supportFragmentManager.popBackStackImmediate()) {
            return true
        }

        return super.onSupportNavigateUp()
    }
}
root_preferences.xml

<PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <PreferenceCategory app:title="App Settings">
        <Preference
            app:fragment="com.example.TestApp.SettingsActivity$Screen1PreferencesFragment"
            app:summary="Multi pref screen1"
            app:title="Screen 1" />

        <Preference
            app:fragment="com.example.TestApp.SettingsActivity$Screen2PreferencesFragment"
            app:summary="Multi pref screen2"
            app:title="Screen 2" />
    </PreferenceCategory>
</PreferenceScreen>
screen1_preferences.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <PreferenceCategory app:title="Screen 1">
        <Preference
            android:clickable="false"
            app:enabled="false"
            app:summary="This is screen 1"
            app:title="Screen 1" />
    </PreferenceCategory>
</PreferenceScreen>
screen2_preferences.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <PreferenceCategory app:title="Screen 2">
        <Preference
            android:clickable="false"
            app:enabled="false"
            app:summary="This is screen 2"
            app:title="Screen 2" />
    </PreferenceCategory>
</PreferenceScreen>

在应用发布时,Google 的自动测试人员报告了以下可能相关的崩溃堆栈跟踪:

androidx.fragment.app.Fragment$InstantiationException: 
  at androidx.fragment.app.FragmentFactory.loadFragmentClass (FragmentFactory.java:57)
  at androidx.fragment.app.Fragment.instantiate (Fragment.java:8)
  at androidx.fragment.app.FragmentContainer.instantiate (FragmentContainer.java:2)
  at androidx.fragment.app.FragmentManager.instantiate (FragmentManager.java:2)
  at com.example.TestApp.SettingsActivity.onPreferenceStartFragment (SettingsActivity.java:2)
  at androidx.preference.PreferenceFragmentCompat.onPreferenceTreeClick (PreferenceFragmentCompat.java:8)
  at androidx.preference.Preference.performClick (Preference.java:8)
  at androidx.preference.Preference.performClick (Preference.java:8)
  at androidx.preference.Preference.onClick (Preference.java:2)
  at android.view.View.performClick (View.java:7140)
  at android.view.View.performClickInternal (View.java:7117)
  at android.view.View.access00 (View.java:801)
  at android.view.View$PerformClick.run (View.java:27351)
  at android.os.Handler.handleCallback (Handler.java:883)
  at android.os.Handler.dispatchMessage (Handler.java:100)
  at android.os.Looper.loop (Looper.java:214)
  at android.app.ActivityThread.main (ActivityThread.java:7356)
  at java.lang.reflect.Method.invoke (Method.java)
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:492)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:930)
Caused by: java.lang.ClassNotFoundException: 
  at java.lang.Class.classForName (Class.java)
  at java.lang.Class.forName (Class.java:454)
  at androidx.fragment.app.FragmentFactory.loadClass (FragmentFactory.java:2)
  at androidx.fragment.app.FragmentFactory.loadFragmentClass (FragmentFactory.java:2)
  at androidx.fragment.app.Fragment.instantiate (Fragment.java:8)
  at androidx.fragment.app.FragmentContainer.instantiate (FragmentContainer.java:2)
  at androidx.fragment.app.FragmentManager.instantiate (FragmentManager.java:2)
  at com.example.TestApp.SettingsActivity.onPreferenceStartFragment (SettingsActivity.java:2)
  at androidx.preference.PreferenceFragmentCompat.onPreferenceTreeClick (PreferenceFragmentCompat.java:8)
  at androidx.preference.Preference.performClick (Preference.java:8)
  at androidx.preference.Preference.performClick (Preference.java:8)
  at androidx.preference.Preference.onClick (Preference.java:2)
  at android.view.View.performClick (View.java:7140)
  at android.view.View.performClickInternal (View.java:7117)
  at android.view.View.access00 (View.java:801)
  at android.view.View$PerformClick.run (View.java:27351)
  at android.os.Handler.handleCallback (Handler.java:883)
  at android.os.Handler.dispatchMessage (Handler.java:100)
  at android.os.Looper.loop (Looper.java:214)
  at android.app.ActivityThread.main (ActivityThread.java:7356)
  at java.lang.reflect.Method.invoke (Method.java)
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:492)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:930)

编辑:供将来参考 - 我能够获得完整的错误日志:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.TestApp, PID: 20293
    androidx.fragment.app.Fragment$e: Unable to instantiate fragment com.example.TestApp.SettingsActivity$Screen1PreferencesFragment: make sure class name exists
        at a.j.d.i.d(:91)
        at androidx.fragment.app.Fragment.instantiate(:546)
        at a.j.d.f.a(:57)
        at a.j.d.m$c.a(:390)
        at com.example.TestApp.SettingsActivity.e(:370)
        at a.n.g.q(:407)
        at androidx.preference.Preference.h0(:1192)
        at androidx.preference.Preference.i0(:1166)
        at androidx.preference.Preference$a.onClick(:181)
        at android.view.View.performClick(View.java:7125)
        at android.view.View.performClickInternal(View.java:7102)
        at android.view.View.access00(View.java:801)
        at android.view.View$PerformClick.run(View.java:27336)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
     Caused by: java.lang.ClassNotFoundException: com.example.TestApp.SettingsActivity$Screen1PreferencesFragment
        at java.lang.Class.classForName(Native Method)
        at java.lang.Class.forName(Class.java:454)
        at a.j.d.i.c(:47)
        at a.j.d.i.d(:88)
        at androidx.fragment.app.Fragment.instantiate(:546) 
        at a.j.d.f.a(:57) 
        at a.j.d.m$c.a(:390) 
        at com.example.TestApp.SettingsActivity.e(:370) 
        at a.n.g.q(:407) 
        at androidx.preference.Preference.h0(:1192) 
        at androidx.preference.Preference.i0(:1166) 
        at androidx.preference.Preference$a.onClick(:181) 
        at android.view.View.performClick(View.java:7125) 
        at android.view.View.performClickInternal(View.java:7102) 
        at android.view.View.access00(View.java:801) 
        at android.view.View$PerformClick.run(View.java:27336) 
        at android.os.Handler.handleCallback(Handler.java:883) 
        at android.os.Handler.dispatchMessage(Handler.java:100) 
        at android.os.Looper.loop(Looper.java:214) 
        at android.app.ActivityThread.main(ActivityThread.java:7356) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) 
     Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.TestApp.SettingsActivity$Screen1PreferencesFragment" on path: DexPathList[[zip file "/data/app/com.example.TestApp-Y6977dm5oijKMZmKaT4_3A==/base.apk"],nativeLibraryDirectories=[/data/app/com.example.TestApp-Y6977dm5oijKMZmKaT4_3A==/lib/x86, /system/lib, /system/product/lib]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:196)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
        at java.lang.Class.classForName(Native Method) 
        at java.lang.Class.forName(Class.java:454) 
        at a.j.d.i.c(:47) 
        at a.j.d.i.d(:88) 
        at androidx.fragment.app.Fragment.instantiate(:546) 
        at a.j.d.f.a(:57) 
        at a.j.d.m$c.a(:390) 
        at com.example.TestApp.SettingsActivity.e(:370) 
        at a.n.g.q(:407) 
        at androidx.preference.Preference.h0(:1192) 
        at androidx.preference.Preference.i0(:1166) 
        at androidx.preference.Preference$a.onClick(:181) 
        at android.view.View.performClick(View.java:7125) 
        at android.view.View.performClickInternal(View.java:7102) 
        at android.view.View.access00(View.java:801) 
        at android.view.View$PerformClick.run(View.java:27336) 
        at android.os.Handler.handleCallback(Handler.java:883) 
        at android.os.Handler.dispatchMessage(Handler.java:100) 
        at android.os.Looper.loop(Looper.java:214) 
        at android.app.ActivityThread.main(ActivityThread.java:7356) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) 
I/Process: Sending signal. PID: 20293 SIG: 9
Disconnected from the target VM, address: 'localhost:8607', transport: 'socket'

感谢@heX 在这方面为我指明了正确的方向。要复制 Android Studio AVD 中的错误,请在 build.gradle 中的 buildTypes 中添加以下代码(模块:app)

buildTypes {
    debug {
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}

运行 您的应用程序处于调试模式,当您触发它时它会显示错误。 在这种特殊情况下的解决方案是将以下内容添加到 proguard-rules.pro 文件中:

-keep class * extends androidx.fragment.app.Fragment { public *; }

我会把它留给聪明的人来解释为什么它有效。或者,如果您不介意失去缩小的好处,您可以在 build.gradle 中设置 minifyEnabled false