java - 无法在 API 23 及更低版本上下载 PDF 文件

标签 java android download android-download-manager

我正在尝试在我的应用程序中添加一个类,通过它我可以在 API 23 及更低版本上下载不同类型的文件而不是 pdf。

我已经在 API 24 及更高版本上测试了我的代码,我可以轻松下载 pdf 文件,但我不知道为什么它不能在 API <= 23 上运行。

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”类,但当我开始在 API <= 23 上下载 pdf 文件时,它返回“失败”。

如何解决 API <= 23 上的此问题?!!

提前致谢。

最佳答案

将您的 minSdkVersion 设置为 15。这将使您的应用与设备 API 15 及更高版本兼容

关于java - 无法在 API 23 及更低版本上下载 PDF 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58046083/

相关文章:

android - 检测您是否距离兴趣点一公里

java - 在闪屏期间动态选择 Activity

java - 我如何在 java 中创建对象的副本,而不是指针

java - 多线程的新手 - 多线程的最具成本效益的方法?

java - 提高 Android 中的文件保存性能

javascript - 使用 Python 中的请求从 __doPostBack 下载文本文件

android - 列出Android手机下载目录下的文件

node.js - 如何知道文件下载何时完成?

java - 如何使用 BufferedReader 读取 CR LF 行?

java - FileNotFound 错误(JSON 文件)