Android 9.0 适配指南

2020-05-20  本文已影响0人  卡路fly

1.Http请求

在9.0中默认情况下启用网络传输层安全协议 (TLS),默认情况下已停用明文支持。

解决办法:解决方法是需要我们添加网络安全配置。首先在 res 目录下新建xml文件夹,添加network_security_config.xml文件

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true" />
</network-security-config>

AndroidManifes.xml 中的application添加

<?xml version="1.0" encoding="utf-8"?>
<manifest ... >
    <application android:networkSecurityConfig="@xml/network_security_config">
          ...
    </application>
</manifest>

为了安全灵活,我们可以指定支持的http域名:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<!-- Android 9.0 上部分域名时使用 http -->
<domain-config cleartextTrafficPermitted="true">
    <domain includeSubdomains="true">secure.example.com</domain>
    <domain includeSubdomains="true">cdn.example1.com</domain>
</domain-config>
</network-security-config>

2.Apache HTTP 客户端弃用

在 Android 6.0 时,就已经取消了对 Apache HTTP 客户端的支持。从 Android 9.0 开始,默认情况下该库已从 bootclasspath 中移除。但是耐不住有些SDK中还在使用,比如我见到的友盟QQ分享报错问题。
所以要想继续使用Apache HTTP,需要在应用的 AndroidManifest.xml 文件中添加:

<uses-library android:name="org.apache.http.legacy" android:required="false"/>

3.前台服务

9.0 要求创建一个前台服务需要请求 FOREGROUND_SERVICE 权限,否则系统会引发 SecurityException。

Intent intentService = new Intent(this, MyService.class);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
    startForegroundService(intentService);
} else {
    startService(intentService);
}

PS:表忘记AndroidManifest.xml中添加FOREGROUND_SERVICE权限

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

巨坑问题:

android9.0 程序置入后台或休眠麦克风不工作解决方法

解决办法:使用startForegroundService

      Intent intent = new Intent(MyApplication.context, MyService.class);
       
        try {
            if (Build.VERSION.SDK_INT >= 26) {
                MyApplication.context.startForegroundService(intent);
            } else {
                MyApplication.context.startService(intent);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

4.启动Activity

在9.0 中,不能直接非 Activity 环境中(比如Service,Application)启动 Activity,否则会崩溃报错。
这类问题一般会在点击推送消息跳转页面这类场景,解决方法就是 Intent 中添加标志FLAG_ACTIVITY_NEW_TASK

Intent intent = new Intent(this, TestActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
上一篇 下一篇

猜你喜欢

热点阅读