下载管理器 returns 在 Android 9.0 NetworkSecurityConfig 上下载失败:未指定网络安全配置,使用平台默认值

Download Manager returns unsuccessful download on Android 9.0 NetworkSecurityConfig: No Network Security Config specified, using platform default

我正在使用下载管理器从 Internet 下载文件。下载在 Android 6、8.1 中成功完成,但在 Android 9.0

中未成功
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDescription("Downloading...");
request.setTitle(nameOfFile);
request.setMimeType("application/pdf");
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS + "/CPG", nameOfFile);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
queueId = manager.enqueue(request);

我通过这里找到了解决方案:

总之,我只需要做到以下几点:

1.createres/xml/network_security_config.xml,然后加上

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

2。在清单文件中,在应用程序标签中引用它

android:networkSecurityConfig="@xml/network_security_config"

欲了解更多信息,请阅读此处:https://developer.android.com/training/articles/security-config#CleartextTrafficPermitted

这个标签对我有用

 android:usesCleartextTraffic="true"

将此标签添加到应用程序中

 <application
        android:name=".ApplicationClass"
        android:allowBackup="true"
        android:hardwareAccelerated="false"
        android:usesCleartextTraffic="true"

解决方案 2)

创建 XML res/xml/network_security_config.xml

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

在你的标签Application里面AndroidManifest.xml

android:networkSecurityConfig="@xml/network_security_config"