Android 5.0(API 21)以下系统兼容(retrofit、okhttp)

近期项目需在一台Android 4.2的终端上运行,结果尴尬了,直接起不来。。

而且是唐僧取经,问题干掉一个,又冒出一个,特此记录。。

第一个报错信息如下(取经第一难):

问题点:Caused by: java.lang.ClassNotFoundException: Didn't find class "androidx.core.content.FileProvider"

经检查发现FileProvider相关的配置都正确,还是找不到,猜测应该是dex分包的问题

解决方案:

在app的build.gradle添加

implementation "androidx.multidex:multidex:2.0.1"

application继承androidx.multidex.MultiDexApplication,或者在你的application类中复写

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(base);
    }

然后在AndroidManifest.xml中关联你的application,如下

<application
    android:name="你的application"
    ...>
    ...
</application>

再在 gradle.properties 文件中添加

android.enableJetifier=true

重新构建项目,运行后可以解决

第二个报错信息如下(取经第二难):

 重要的来了,或者正题来了。。

问题点:Expected Android API level 21+ but was 17

      原来,作为安卓app开发平台使用最为广泛的网络框架okhttp,从okhttp3.13版本起,就要求android最低版本必须为android5.0(21),而对于依然使用比较广泛的低版本2.3+,则需要停留在3.12.x版本,官方将会为其支持到今年2020年12月30日,详见OkHttp 3.13 Requires Android 5+

      那么,如何解决这个问题呢,有两种方案,要么降低okhttp版本,要么做兼容

      我采用的是降低okhttp版本到3.12,简单,暴力

    api 'com.squareup.okhttp3:okhttp:3.12.0'
    api 'com.squareup.okhttp3:logging-interceptor:3.12.0'
    api 'com.squareup.okio:okio:1.14.0'

别忘了在build.gradle 中添加如下代码,增加对Httpclink的支持 

 android {
        useLibrary 'org.apache.http.legacy'
 ...
    }

第三个报错信息如下(取经第三难):

 问题点:java.lang.VerifyError: okhttp3/internal/platform/Android10Platform

原因是 retrofit 内也包含了较高版本的okhttp,需要排除

    api ('com.squareup.retrofit2:retrofit:2.9.0'){
        exclude group: 'com.squareup.okhttp3', module: 'okhttp'
    }
    api ('com.squareup.retrofit2:converter-gson:2.9.0'){
        exclude group: 'com.squareup.okhttp3', module: 'okhttp'
    }
    api ('com.squareup.retrofit2:adapter-rxjava2:2.9.0'){
        exclude group: 'com.squareup.okhttp3', module: 'okhttp'
    }

第四个报错信息如下(取经第四难):

问题点:Binary XML file line #21: Error inflating class TextView 

 原因是 xml 文件中包含了 drawableTop 属性,该属性在太低的Android api 中也不支持,去掉换种方式即可。

到此,取经成功,项目在 Android 4.2 版本上完美运行!

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值