Akash Dubey
Akash Dubey

Reputation: 1538

File Download from Webview is not working in android, I am trying this way,

Below is my Code for implementing a webview which opens a link which have tabular information on date selection and having three buttons in the bottom for downloading pdf, xls and doc file download works well in browser but in webview download is not happening!

public class Reports_Visit_Statastics extends AppCompatActivity {

WebView wb;
String ReportsURL, title;
@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.visit_statastics_reports);
    wb = (WebView) findViewById(webView);
    wb.getSettings().setLoadsImagesAutomatically(true);
    wb.getSettings().setJavaScriptEnabled(true);
    wb.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
    Bundle b = getIntent().getExtras();
    ReportsURL = b.getString("URL");
    title = b.getString("title");
    initToolbar();
    wb.setWebViewClient(new MyWebViewClient());
    wb.loadUrl(ReportsURL);

}

private class MyWebViewClient extends WebViewClient {
    @Override
    public void onReceivedError(WebView view, int errorCode,
                                String description, String failingUrl) {
        Log.d("WEB_VIEW_TEST", "error code:" + errorCode + " - " + description);
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        // handle different requests for different type of files
        // this example handles downloads requests for .apk and .mp3 files
        // everything else the webview can handle normally
        if (url.endsWith(".pdf")) {
            Uri source = Uri.parse(url);
            // Make a new request pointing to the .apk url
            DownloadManager.Request request = new DownloadManager.Request(source);
            // appears the same in Notification bar while downloading
            request.setDescription("Description for the DownloadManager Bar");
            request.setTitle("Document");

                request.allowScanningByMediaScanner();
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

            // save the file in the "Downloads" folder of SDCARD
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "Document.doc");
            // get download service and enqueue file
            DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
            manager.enqueue(request);
        } else if (url.endsWith(".doc")) {
            Uri source = Uri.parse(url);
            // Make a new request pointing to the .apk url
            DownloadManager.Request request = new DownloadManager.Request(source);
            // appears the same in Notification bar while downloading
            request.setDescription("Description for the DownloadManager Bar");
            request.setTitle("Document");

                request.allowScanningByMediaScanner();
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

            // save the file in the "Downloads" folder of SDCARD
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "Document.doc");
            // get download service and enqueue file
            DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
            manager.enqueue(request);
        } else if (url.endsWith(".xls")) {
            Uri source = Uri.parse(url);
            // Make a new request pointing to the .apk url
            DownloadManager.Request request = new DownloadManager.Request(source);
            // appears the same in Notification bar while downloading
            request.setDescription("Description for the DownloadManager Bar");
            request.setTitle("Document");

                request.allowScanningByMediaScanner();
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

            // save the file in the "Downloads" folder of SDCARD
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "Document.doc");
            // get download service and enqueue file
            DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
            manager.enqueue(request);
        }
        // if there is a link to anything else than .apk or .mp3 load the URL in the webview
        else view.loadUrl(url);
        return true;
    }
}


private void initToolbar() {

    final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    final ActionBar actionBar = getSupportActionBar();

    try {
        if (actionBar != null) {
            actionBar.setTitle(title);
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    } catch (Exception e) {
        Log.d("Doctor_master", e.toString());
    }
}



@Override

public void onBackPressed() {

    super.onBackPressed();
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == android.R.id.home) {
        onBackPressed();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

}

Upvotes: 3

Views: 6694

Answers (1)

Anurag Singh
Anurag Singh

Reputation: 6190

Based on the comments and discussion from the chat.

I have noticed that shouldOverrideUrlLoading is not being called. As, per the android documentation shouldOverrideUrlLoading

Give the host application a chance to take over the control when a new url is about to be loaded in the current WebView

But in your case since url doesn't change in WebView address bar while clicking any of the three links. It just call javascript code javascript:__doPostBack('lnkPDF',''), which calls the post method to generate the file. If you to want use DownloadManager to download file while showing notification in notification area, you need to create dynamic static url for files like http:// or https://. E.g. http://www.somedomain/may_be_session_id/some_random_file_number_valid_for_some_time_only/file_name.pdf.

In addition to the above, let the web page change or redirect to new url, only then you will be able to capture urls in shouldOverrideUrlLoading.

Try changing your implementation of return in shouldOverrideUrlLoading to True if the host application wants to leave the current WebView and handle the url itself, otherwise return false.

Upvotes: 4

Related Questions