AndroidX 踩坑指南

作者: Android轮子哥 | 来源:发表于2021-04-24 20:44 被阅读0次

    本文章已授权鸿洋微信公众号转载

    官方文档

    转 AndroidX 的原因

    • 主动原因:Support 包从 API 28 (Android 9.0)已经弃更,取而代之的是谷歌新推出的 AndroidX 的包。

    • 被动原因:现在一些第三方库都是直接依赖 AndroidX 包,由于谷歌限制 Support 包和 AndroidX 包不能共存的机制,导致我们无法直接依赖第三方库的最新版本,例如某个框架的最新版的依赖就是基于 AndroidX 包,这样就导致我们只能去依赖旧版的框架,并且后续一旦出现问题将无法直接升级框架的方式来解决,而是必须要先将项目升级到 AndroidX 才能升级框架的版本,这个时候我们就会显得很被动。

    转成 AndroidX 的步骤

    Studio 帮我们做了什么事?

    • 自动替换导入类和 xml 中的 View 包名
    import android.support.v7.app.AppCompatActivity;
    import androidx.appcompat.app.AppCompatActivity;
    
    <android.support.v7.widget.RecyclerView />
    <androidx.recyclerview.widget.RecyclerView />
    
    • Support 远程依赖变化
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support:design:28.0.0'
    
    implementation 'androidx.appcompat:appcompat:1.0.0'
    implementation 'com.google.android.material:material:1.0.0'
    
    • gradle.properties 配置变化
    # 表示使用 AndroidX
    android.useAndroidX = true
    # 表示将第三方库迁移到 AndroidX
    android.enableJetifier = true
    

    坑一:找不到约束布局

    • 这个因为 AndroidX 包中并没有依赖 ConstraintLayout 库,只需要手动加入依赖即可
    implementation 'androidx.constraintlayout:constraintlayout:2.0.0'
    

    坑二:导包报错

    • 部分导包报错,只需要手动更换引用的包名即可,这里不指定包名 Studio 自动会帮我们导入默认的

    坑三:第三方库的坑

    • 虽然在这次转换的过程中没有出现过这种异常,但是根据以往的经验,这两个第三方库很可能会导致编译不通过
    implementation 'com.jakewharton:butterknife:9.0.0'
    annotationProcessor 'com.jakewharton:butterknife-compiler:9.0.0'
    
    implementation 'com.github.bumptech.glide:glide:4.7.1'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.7.1'
    
    • 这个是因为这两个库的旧版本依赖 Support 包导致的,所以解决的方式是将这两个库升级到最新版本即可
    implementation 'com.jakewharton:butterknife:10.2.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.1'
    
    implementation 'com.github.bumptech.glide:glide:4.11.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
    

    坑四:替换不干净

    • Studio 只能帮我们替换显式调用的包名,而不能帮我们替换隐式调用的包名,例如通过反射填写的包名,混淆规则等等
    Class.forName("android.support.design.widget.Snackbar");
    Class.forName("android.support.design.widget.BottomSheetDialog");
    

    -keep class android.support.**{*;}
    
    • 解决的方式也很简单,在项目中全局搜索 android.support 关键字眼,然后手动进行替换

    坑五:Fragment 崩溃

    • 升级 AndroidX 后,切换 Fragment 出现 NullPointerException:androidx.fragment.app.FragmentManagerImpl.isDestroyed() 异常,经过排查是 Fragment 基类中存在这些反射的代码导致的
    public abstract class BaseFragment extends Fragment {
    
        @Override
        public void onDetach() {
            super.onDetach();
            try {
                Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
                childFragmentManager.setAccessible(true);
                childFragmentManager.set(this, null);
            } catch (NoSuchFieldException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
    }
    

    坑六:WebView 崩溃

    • 升级 AndroidX 之后,Android 5.x 的设备上出现了此异常,并且这个 Bug 是必现的
    android.view.InflateException: Binary XML file line #20: Error inflating class android.webkit.WebView
        at android.view.LayoutInflater.createView(LayoutInflater.java:633)
        at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:55)
        at android.view.LayoutInflater.onCreateView(LayoutInflater.java:682)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:741)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:809)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
    
    • 经过验证是 AndroidX 1.1.0 版本导致的,这个版本的 AndroidX 和 WebView 存在冲突
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'com.google.android.material:material:1.1.0'
    
    • 解决的方式大致分为以下两种,大家可以根据实际情况选择。

    • 方法一:将 AndroidX 相关依赖升级到 1.2.0 版本及以上

    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'com.google.android.material:material:1.2.0'
    
    • 方法二:对 WebView 进行单独修复
    public class LollipopFixedWebView extends WebView {
        
        public LollipopFixedWebView(Context context) {
            super(getFixedContext(context));
        }
    
        public LollipopFixedWebView(Context context, AttributeSet attrs) {
            super(getFixedContext(context), attrs);
        }
    
        public LollipopFixedWebView(Context context, AttributeSet attrs, int defStyleAttr) {
            super(getFixedContext(context), attrs, defStyleAttr);
        }
    
        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        public LollipopFixedWebView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
            super(getFixedContext(context), attrs, defStyleAttr, defStyleRes);
        }
    
        public LollipopFixedWebView(Context context, AttributeSet attrs, int defStyleAttr, boolean privateBrowsing) {
            super(getFixedContext(context), attrs, defStyleAttr, privateBrowsing);
        }
    
        /**
         * 修复原生 WebView 和 AndroidX 在 Android 5.x 上面崩溃的问题
         *
         * doc:https://stackoverflow.com/questions/41025200/android-view-inflateexception-error-inflating-class-android-webkit-webview
         */
        private static Context getFixedContext(Context context) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                // 为什么不用 ContextImpl,因为使用 ContextImpl 获取不到 Activity 对象,而 ContextWrapper 可以
                // 这种写法返回的 Context 是 ContextImpl,而不是 Activity 或者 ContextWrapper
                // return context.createConfigurationContext(new Configuration());
                // 如果使用 ContextWrapper 还是导致崩溃,因为 Resources 对象冲突了
                // return new ContextWrapper(context);
                // 如果使用 ContextThemeWrapper 就没有问题,因为它重写了 getResources 方法,返回的是一个新的 Resources 对象
                return new ContextThemeWrapper(context, context.getTheme());
            }
            return context;
        }
    }
    

    常见误区:FileProvider

    • 关于 FileProvider 的清单注册,没转 AndroidX 之前是这样子的
    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
    
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
    </provider>
    
    • 转成 AndroidX 之后的是这样子的
    <provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
    
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
    </provider>
    
    • 你可能会觉得这里是不是改漏掉了,看着着实不爽
    <provider
        ....
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS" />
    </provider>
    
    • 于是乎你顺手改成了这样,看着着实顺眼多了
    <provider
        ....
        <meta-data
            android:name="androidx.core.FILE_PROVIDER_PATHS" />
    </provider>
    
    • 结果一运行,你会发现应用运行不起来,一看日志才明白报了错
     java.lang.IllegalArgumentException: Missing android.support.FILE_PROVIDER_PATHS meta-data
        at androidx.core.content.FileProvider.parsePathStrategy(FileProvider.java:613)
        at androidx.core.content.FileProvider.getPathStrategy(FileProvider.java:579)
        at androidx.core.content.FileProvider.attachInfo(FileProvider.java:392)
    
    • 结果你一点进去看源码,才发现这是个雷
    package androidx.core.content;
    
    public class FileProvider extends ContentProvider {
    
        private static final String
                META_DATA_FILE_PROVIDER_PATHS = "android.support.FILE_PROVIDER_PATHS";
    
        private static PathStrategy parsePathStrategy(Context context, String authority) {
            final XmlResourceParser in = info.loadXmlMetaData(
                context.getPackageManager(), META_DATA_FILE_PROVIDER_PATHS);
            if (in == null) {
                throw new IllegalArgumentException(
                        "Missing " + META_DATA_FILE_PROVIDER_PATHS + " meta-data");
            }
        }
    }
    
    • 这个故事告诉我们,闲着没事不要做一些骚操作,有空不如多学习

    灰度小插曲

    • 发布灰度更新之后,我们在 Bugly 上面发现了一个崩溃率直线上升的 Bug
    异常名称 发生次数 影响设备数
    java.lang.ClassNotFoundException:
    android.support.constraint.ConstraintLayout
    14 7
    • 经过排查发现,是我的同事开发分支的代码是 Support 库,合并了 AndroidX 分支的代码之后没有进行复测导致的,再加上 Gradle 编译时不会去检查 Xml 文件中的 View 包名是否正确,所以才出现了这个问题。

    • 于是我们快速发了一个 Hotfix 版本进行修复,值得庆幸的是,这个 Bug 发生在账号注销界面,并不会影响到主流程,否则就是严重的事故了,望大家引以为戒。

    后续情况汇报

    • 正式上线一周后的情况:一切正常,无出现崩溃和用户反馈

    • 正式上线一个月后的情况:一切正常,无出现崩溃和用户反馈

    • 正式上线三个月后的情况:一切正常,无出现崩溃和用户反馈

    Android 技术讨论 Q 群:10047167

    相关文章

      网友评论

        本文标题:AndroidX 踩坑指南

        本文链接:https://www.haomeiwen.com/subject/kfkbqltx.html