DownloadManager имеет огромную задержку с началом загрузки - PullRequest
0 голосов
/ 17 июня 2019

Я использую этот исходный код для загрузки файла в общедоступную и внешнюю директорию "загрузок" Android.

private void download(String url){
    if (ActivityCompat.checkSelfPermission(SectionManager.getInstance().getCurrentActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        PermissionManager.getInstance().requestPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE, PermissionManager.PERMISSION_REQUEST_WRITE_EXTERNAL_STORAGE);
    } else {
        DownloadManager.Request r = new DownloadManager.Request(Uri.parse(url));

        // This put the download in the same Download dir the browser uses
        //r.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, url.substring(url.lastIndexOf('/')+1));
        r.setDestinationInExternalFilesDir(SectionManager.getInstance().getCurrentActivity(), Environment.DIRECTORY_DOWNLOADS, url.substring(url.lastIndexOf('/')+1));

        // When downloading music and videos they will be listed in the player
        // (Seems to be available since Honeycomb only)
        r.allowScanningByMediaScanner();

        // Notify user when download is completed
        // (Seems to be available since Honeycomb only)
        r.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

        // Start download
        DownloadManager dm = (DownloadManager) SectionManager.getInstance().getCurrentActivity().getSystemService(DOWNLOAD_SERVICE);
        dm.enqueue(r);
    }
}

Когда url равен http://mobimento.com/~psaez/video2.zip, эта ошибка выдается в logcat

2019-06-17 19:15:01.916 11623-19923/? D/DownloadManager: [191] Starting
2019-06-17 19:15:02.308 11623-19923/? W/DownloadManager: [191] Stop requested with status HTTP_DATA_ERROR: Failed reading response: java.net.ProtocolException: unexpected end of stream
2019-06-17 19:15:02.310 11623-19923/? D/DownloadManager: [191] Finished with status WAITING_TO_RETRY

Но через 30-40 секунд, а иногда и через 1 или 2 минуты загрузка начинается и заканчивается правильно:

2019-06-17 19:17:42.383 11623-20295/? D/DownloadManager: [192] Starting
2019-06-17 19:17:42.487 11623-20295/? D/DownloadManager: [192] Finished with status SUCCESS

Что не так в коде? Почему выдает ошибку и через 30-40 секунд начинает загружаться?

1 Ответ

0 голосов
/ 17 июня 2019

Попробуйте эти решения и убедитесь, что ваш URL является действительным

Решение 1)

Добавьте android:networkSecurityConfig="@xml/network_security_config" в тег приложения

<application
        android:name=".ApplicationClass"
        android:allowBackup="true"
        android:hardwareAccelerated="false"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:largeHeap="true"
        android:networkSecurityConfig="@xml/network_security_config"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

где network_security_config.xml

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

Создайте xml папку в каталоге res и затем network_security_config.xml в папке XML

Решение 2)

android:usesCleartextTraffic="true"

Добавить этот тег в application тег в manifest файл

<application
        android:name=".ApplicationClass"
        android:allowBackup="true"
        android:hardwareAccelerated="false"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:largeHeap="true"
        android:usesCleartextTraffic="true"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

Ссылка: - Скачать Manger не работает в Android Pie 9.0 (Xiaomi mi A2) a2

...