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

时间:2019-09-22 04:36:40

标签: 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文件时,它返回“ Failed”。

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

谢谢。

1 个答案:

答案 0 :(得分:0)

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