今天做項目時意外發現,已經在AndroidManifest.xml申請網絡權限,在8.0以下的系統中網絡訪問正常,但是9.0中出現網絡請求失敗。
如圖(左是榮耀6x Android8.0,右是一加5 Android9.0):
出現這個錯誤的原因是:從 Android 9 開始,默認情況下該內容庫已從 bootclasspath 中移除且不可用於應用。且Android P 限制了明文流量的網絡請求,非加密的流量請求都會被系統禁止掉。
解決方案
在res目錄下新建一個xml目錄,在xml目錄下新建network_security_config.xml文件,
插入以下代碼
<?xml version="1.0" encoding="utf-8"?> <network-security-config> <base-config cleartextTrafficPermitted="true" /> </network-security-config>
編輯 AndroidManifest.xml節點application
插入代碼:
android:networkSecurityConfig="@xml/network_security_config"
成功解決,以下圖為證
對了,這是使用okhttp3才會出現的,使用httpURLConnectio則不會出現這個問題