Невозможно загрузить файлы PDF на API 23 и ниже - PullRequest
0 голосов
/ 22 сентября 2019

Я пытаюсь добавить класс в своем приложении, с помощью которого я могу загружать файлы другого типа вместо pdf для API 23 и ниже.

Я проверил свои коды на API 24 и выше, и ямогу легко скачать pdf файлы, но я не знаю, почему он не работает с API <= 23. </p>

public class FileDownloader {
    private static final int MEGA_BYTE = 1024 * 1024;

    public interface OnDownloadListener{
        void onStarted();
        void onProgressUpdate(int upd);
        void onFinished(String result);
        void onError(Exception e);
    }

    // usually, subclasses of AsyncTask are declared inside the activity class.
    // that way, you can easily modify the UI thread from here
    public static class DownloadTask extends AsyncTask<String, Integer, String> {

        private Context context;
        private OnDownloadListener onDownloadListener;

        public DownloadTask(Context context, OnDownloadListener onDownloadListener) {
            this.context = context;
            this.onDownloadListener = onDownloadListener;
        }

        @Override
        protected String doInBackground(String... str) {
            // take CPU lock to prevent CPU from going off if the user
            // presses the power button during download
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                    getClass().getName());
            wl.acquire();

            try {
                InputStream input = null;
                OutputStream output = null;
                HttpURLConnection connection = null;
                try {
                    URL url = new URL(str[0]);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.connect();

                    // expect HTTP 200 OK, so we don't mistakenly save error report
                    // instead of the file
                    if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
                        return "Server returned HTTP " + connection.getResponseCode()
                                + " " + connection.getResponseMessage();

                    // this will be useful to display download percentage
                    // might be -1: server did not report the length
                    int fileLength = connection.getContentLength();

                    // download the file
                    input = connection.getInputStream();
                    output = new FileOutputStream(str[1]);  //   /sdcard/file_name.extension

                    byte data[] = new byte[MEGA_BYTE];
                    long total = 0;
                    int count;
                    while ((count = input.read(data)) != -1) {
                        // allow canceling with back button
                        if (isCancelled())
                            return null;
                        total += count;
                        // publishing the progress....
                        if (fileLength > 0) // only if total length is known
                            publishProgress((int) (total * 100 / fileLength));
                        output.write(data, 0, count);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    if(onDownloadListener != null){
                        onDownloadListener.onError(e);
                    }
                    return e.toString();
                }finally {
                    try {
                        if (output != null)
                            output.close();
                        if (input != null)
                            input.close();
                    }catch (IOException ignored) { }

                    if (connection != null)
                        connection.disconnect();
                }
            } finally {
                wl.release();
            }
            return null;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if(onDownloadListener != null){
                onDownloadListener.onStarted();
            }
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);
            // if we get here, length is known, now set indeterminate to fals
            if(onDownloadListener != null){
                onDownloadListener.onProgressUpdate(progress[0]);
            }
        }

        @Override
        protected void onPostExecute(String result) {
            if(onDownloadListener != null){
                onDownloadListener.onFinished(result);
            }
        }
    }
}

Когда «HttpURLConnection» пытается подключиться, он возвращает код ошибки 404, что означает «HTTP 404 Not Found»но на API> = 24 он работает нормально, и я также могу загрузить эти файлы через веб-браузеры.Я также пытался использовать класс «DownloadManager», но он возвращает «Failed», когда я начинаю скачивать PDF-файлы в API <= 23. </p>

Как я могу исправить эту проблему в API <= 23? !! </p>

Заранее спасибо.

1 Ответ

0 голосов
/ 22 сентября 2019

Установите minSdkVersion равным 15. Это сделает ваше приложение совместимым с устройствами API 15 и выше

...