如何使用Android Download Manager下载从链接生成的PDF,而不是直接PDF文件路径

时间:2018-02-21 12:17:38

标签: android pdf android-download-manager

我在Android应用中创建了我的网站的webview。 我在Android中使用Download Manager从我的网站下载PDF文件。但是没有PDF文件的直接链接,而是PDF文件正在生成,因此,我无法下载该文件。下载显示不成功。

我的编码:

 myWebView.setDownloadListener(new DownloadListener() {
                @Override
                public void onDownloadStart(String url, String userAgent,
                                            String contentDisposition, String mimetype,
                                            long contentLength) {
                    try{
                    DownloadManager.Request request = new DownloadManager.Request(
                            Uri.parse(url));

                    if(isExternalStorageWritable() && isExternalStorageReadable()) {
                        request.setTitle("Invoice");
                        request.setDescription("Downloads");
                        request.setVisibleInDownloadsUi(true);
                        request.allowScanningByMediaScanner();
                        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
                        request.setDestinationInExternalFilesDir(MainActivity.this,Environment.DIRECTORY_DOWNLOADS, "invoice.pdf");//download to internal memory

                        DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                        dm.enqueue(request);
                        Toast.makeText(getApplicationContext(), "Downloading File", //To notify the Client that the file is being downloaded
                                Toast.LENGTH_LONG).show();
                    }
                    else {
                        Toast.makeText(getApplicationContext(), "No SD Card Present.."+Environment.DIRECTORY_DOWNLOADS, //To notify the Client that the file is being downloaded
                                Toast.LENGTH_LONG).show();
                    }

                    }
                    catch (Exception e)
                    {
                        Log.d("Caught inside uri", e.toString());
                    }
                }
            });// checks for downloads

1 个答案:

答案 0 :(得分:0)

要获得回应

 val request = InputStreamVolleyRequest(Request.Method.POST, url, object : Response.Listener<ByteArray> {
            override fun onResponse(response: ByteArray?) {
                Log.d("Response ", response.toString())
                //val str = save(response)
                abaraResponse.onSuccess(methodName, response)
                stopService()

                //Log.d("Response ", str)
            }
        },
                object : Response.ErrorListener {
                    override fun onErrorResponse(error: VolleyError?) {
                        Log.d("Response ", error.toString())
                        abaraResponse.onError(methodName, error)
                        stopService()
                    }
                }, headerMap, body)

这是输入流请求类:

public class InputStreamVolleyRequest extends Request<byte[]> {
    private final Response.Listener<byte[]> mListener;
    private Map<String, String> mParams;
    private JSONObject mBody;

    //create a static map for directly accessing headers
    public Map<String, String> responseHeaders ;

    public InputStreamVolleyRequest(int method, String mUrl , Response.Listener<byte[]> listener,
                                    Response.ErrorListener errorListener, HashMap<String, String> params, JSONObject body) {
        // TODO Auto-generated constructor stub

        super(method, mUrl, errorListener);
        // this request would never use cache.
        setShouldCache(false);
        mListener = listener;
        mParams=params;
        mBody = body;
    }

    @Override
    public byte[] getBody() throws AuthFailureError {

        return mBody.toString().getBytes();

    }

    @Override
    public Map<String, String> getHeaders()
            throws com.android.volley.AuthFailureError {
        return mParams;
    };


    @Override
    protected void deliverResponse(byte[] response) {
        mListener.onResponse(response);
    }

    @Override
    protected Response<byte[]> parseNetworkResponse(NetworkResponse response) {

        //Initialise local responseHeaders map with response headers received
        responseHeaders = response.headers;

        //Pass the response data here
        return Response.success( response.data, HttpHeaderParser.parseCacheHeaders(response));
    }
}

使用以下代码从下载的bytearray中获取pdf:

fun save(response: ByteArray?): String {
        val path: String = Environment.getExternalStorageDirectory().path + "/" + pdfname+ ".pdf"
        var f1 = File(path);
        try {
            val bos = BufferedOutputStream(FileOutputStream(f1))
            bos.write(response)
            bos.flush()
            bos.close()


        } catch (e: FileNotFoundException) {
            e.printStackTrace();
        } catch (e: IOException) {
            e.printStackTrace();
        }

        return f1.path; // I like to return it because i can use it to start a "open file" intent
    }

然后使用pdfViewer库设置您对pdf viewer的响应

pdfView.fromFile(File(/*from save*/ ))
                .defaultPage(1)
                .showMinimap(false)
                .enableSwipe(true)
                .load()

pdf库是compile 'com.joanzapata.pdfview:android-pdfview:1.0.4@aar'