我在 Android 11 OnePlus 设备中遇到崩溃,如何解决?

I'm getting below crash in Android 11 OnePlus Device, How to fix this?

从包管理器获取应用程序信息导致应用程序崩溃,为什么会发生这种情况以及如何解决?

错误代码

Fatal Exception: java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
   at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:641)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:978)
Caused by android.content.pm.PackageManager$NameNotFoundException: com.mi.android.globalfileexplorer
   at android.app.ApplicationPackageManager.getApplicationInfoAsUser(ApplicationPackageManager.java:428)
   at android.app.ApplicationPackageManager.getApplicationInfo(ApplicationPackageManager.java:417)
 at com.example.mediapicker.ui.FolderListFragment.setMenuItems(FolderListFragment.kt:92)
   at com.example.mediapicker.ui.FolderListFragment.onPrepareOptionsMenu(FolderListFragment.kt:84)
   at androidx.fragment.app.Fragment.performPrepareOptionsMenu(Fragment.java:3112)
   at androidx.fragment.app.FragmentManager.dispatchPrepareOptionsMenu(FragmentManager.java:3212)
   at androidx.fragment.app.Fragment.performPrepareOptionsMenu(Fragment.java:3114)

应用代码

 private fun setMenuItems(apps: MutableList<String>, menu: Menu) {
    menu.clear()
    val pm = requireContext().packageManager
    apps.forEachIndexed { index, packageName ->
        val appInfo = pm.getApplicationInfo(
            packageName,
            PackageManager.GET_META_DATA
        )
        menu.add(
            0, index, Menu.NONE, pm.getApplicationLabel(appInfo)
        ).icon = pm.getApplicationIcon(packageName)
        if (menu is MenuBuilder) {
            menu.setOptionalIconsVisible(true)
        }
    }
}

清单文件

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mediapicker">

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" />

<application>
    <activity
        android:name=".ui.MediaPickerActivity"
        android:label="@string/title_activity_media_picker"
        android:theme="@style/ef_ImagePickerTheme"/>
</application>

<queries>
    <intent>
        <action android:name="android.intent.action.PICK" />
        <data android:mimeType="video/*, image/*" />
    </intent>
</queries>

我在我的应用程序中 运行 以上代码,但我在 One Plus 设备中遇到此崩溃如何解决?

documentation

中所述

getApplicationInfo Throws PackageManager.NameNotFoundException if a package with the given name cannot be found on the system.

在您的情况下,您正在寻找 com.mi.android.globalfileexplorer,这是您的 OnePlus 设备上未安装的小米文件资源管理器应用程序。

处理异常并避免在抛出时将项目添加到菜单中。