0

this method is called from oncreate() of the activity. what code should I write in order to make download happen? currently, from this code, the webview is visible with two buttons in end of it . after clicking on them download doesn't happen. please help

private void openBrowser() 
{
    Uri uri = Uri.parse("googlechrome://navigate?url=" + urlString + mSelectedProductDetails.getTransIdValue());
    Intent i = new Intent(Intent.ACTION_VIEW, uri);
    // final String message;
    if (i.resolveActivity(getActivity().getPackageManager()) == null) {
        i.setData(Uri.parse(urlString + mSelectedProductDetails.getTransIdValue()));
        message = urlString + mSelectedProductDetails.getTransIdValue();
    }else 
    {
        message = urlString+mSelectedProductDetails.getTransIdValue();}
        webView.setWebViewClient(new WebViewClient());
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().getJavaScriptEnabled();
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        progress.setVisibility(View.INVISIBLE);
        webView.loadUrl(message);
    }
}
Komal12
  • 3,340
  • 4
  • 16
  • 25
shantanu more
  • 11
  • 2
  • 7

1 Answers1

0

To download a file you need to implement DownloadListener in WebView.

webView.setDownloadListener(new DownloadListener() {

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

        mUrl = url;
        mUserAgent = userAgent;
        mContentDisposition = contentDisposition;
        mMimetype = mimetype;
        mContentLength = contentLength;

        if (isStoragePermissionGranted()) {
            downloadFile(url, userAgent, contentDisposition, mimetype, contentLength);
        }
    }
});

To download your file

public void downloadFile(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,
            (URLUtil.guessFileName(url, contentDisposition, mimetype)));
    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();
}
Kunu
  • 5,078
  • 6
  • 33
  • 61