• 解决android 9上无法使用http协议


    用户反应本来好用的app,突然无法访问服务器,不能正常用了,拿到手机,从头检查权限,重新安装都不能解决,网络是正常的,怎么就不能访问网络了呢?所有想到的办法都用了而不能解决,最后想起看一下android版本,原来升级到9了!

    看Delphi上如何解决这个问题:

    第一步:制作配置文件network_security_config.xml,下面是内容:

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

    然后在项目文件夹建一个子文件夹res/xml,把network_security_config.xml保存到res/xml下。

    第二步:.修改项目的AndroidManifest.template文件

    下面是我修改的结果,在applicaiton段增加了networkSecurityConfig一行

        <application android:persistent="%persistent%"
            android:restoreAnyVersion="%restoreAnyVersion%"
            android:label="%label%"
            android:debuggable="%debuggable%"
            android:largeHeap="%largeHeap%"
            android:icon="%icon%"
            android:theme="%theme%"
            android:hardwareAccelerated="%hardwareAccelerated%"
            android:networkSecurityConfig="@xml/network_security_config"
            >

    在application段,增加一行,引用第一步制作的文件network_security_config.xml

    android:networkSecurityConfig="@xml/network_security_config"

    注意:一定要写对位置,我就犯了错,因为没写对,浪费几个小时。

    第三步:发布network_security_config.xml

    通过Project->Deployment菜单,打开发布文件窗口,把 network_security_config.xml加进去,如下图:

    注意,发布文件路径,即Remote Path为resxml

    保存后,重新编译项目,正常情况下,问题就解决了。

    如果以前编译过项目,为了要重新生成AndroidManifest.xml文件,你可以Clear项目,也可以手工把生成过的AndroidManifest.xml删除,这个文件在AndroidRelease文件夹中。手工删除,会减少编译的时间。

    这一步也非常重要,我就遇到不重新生成AndroidManifest.xml的问题。

    关于原理,下面这篇文章写的非常好,感兴趣可以参考:

    https://blog.csdn.net/gengkui9897/article/details/82863966

    最后,感谢ChinaCock作者提醒我参考他写的视频播放Demo app,里面就是这样实现的。

    如果你不知道ChinaCock是什么?可以看我写过的对ChinaCock组件使用说明的文章,也可以加入他的官方群223717588去进一步了解。如果没项目,没钱,就不用去了,没有免费版本来学习。

    后记:高勇针对上面的实现,给了更简单的实现方法,以下为他写的原文:

    解决安卓9不让客户端通过非https方式访问服务端数据(不允许发送明文http请求)的问题。

    1、选择安卓平台编译一次程序,在项目根目录下会生成如下文件AndroidManifest.template.xml
    2、打开此文件,在正确位置加上以下权限即可:android:usesCleartextTraffic="true"

    类似如下:

    <application android:persistent="%persistent%" 
            android:restoreAnyVersion="%restoreAnyVersion%" 
            android:label="%label%" 
            android:debuggable="%debuggable%" 
            android:largeHeap="%largeHeap%"
            android:icon="%icon%"
            android:theme="%theme%"
            android:hardwareAccelerated="%hardwareAccelerated%"
    
        android:usesCleartextTraffic="true"
    
            android:resizeableActivity="false">

    直接在AndroidManifest.template.xml中定义使用http访问,确实简单!

    下面这篇文章,分析更透,可以进一步参考学习:

    源码分析 Android 9.0 http请求适配原理

  • 相关阅读:
    Daily Scrum (2015/10/28)
    Dailu Scrum (2015/10/27)
    wenbao与cmd
    wenbao与IIS
    wenbao与模板
    wenbao与git
    wenbao与vscode
    wenbao与矩阵
    wenbao与面试题
    wenbao 与将linux系统(kali)装入U盘
  • 原文地址:https://www.cnblogs.com/kinglandsoft/p/10610707.html
Copyright © 2020-2023  润新知