AndroidX 踩坑指南

本文章已授權鴻洋微信公眾號轉載

官方文檔

轉 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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,825評論 6 546
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,814評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,980評論 0 384
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 64,064評論 1 319
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,779評論 6 414
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 56,109評論 1 330
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 44,099評論 3 450
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 43,287評論 0 291
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,799評論 1 338
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,515評論 3 361
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,750評論 1 375
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,221評論 5 365
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,933評論 3 351
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,327評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,667評論 1 296
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,492評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,703評論 2 380

推薦閱讀更多精彩內容