How to download PDF file through Android Web View?

Issue

I have an android web view which works perfectly fine.
I added the below code to download the PDF file.

webview.setDownloadListener(new DownloadListener() {

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

                request.allowScanningByMediaScanner();
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "Name of your downloadble file goes here, example: Mathematics II ");
                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();

            }
        });

Although it works perfectly fine on the web,

But in Android Webview App :

  • It gives me an in-app notification of "Downloading File"
  • Shows the loader for a while
  • Then a notification on the notification bar says "Download Unsuccessful" from Download Manager
  • Please note that I have also given permission in Manifest as well.

For the full code of MainActivity.java please refer to the link.

Any help is greatly appreciated.

Solution

This guy from youtube solved it for me.

public void onDownloadStart(String url, String userAgent,
                                        String contentDisposition, String mimetype,
                                        long contentLength) {

                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setData(Uri.parse(url));
                startActivity(i);
   }
});

But the issue is that the app is redirecting to chrome to load the URL and letting me download the file. Is there any other way to load the URL in the background and download the file?

Hope it helps someone..

Answered By – Harry

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published