You need to override the shouldOverrideUrlLoading method in the WebClient. I use this approach with a combination of intent and Google Docs as a backup:
/* You might want to move this string definition somewhere else */ final String googleDocs = "https://docs.google.com/viewer?url="; WebView webView = new WebView(getContext()); //webView.getSettings().setJavaScriptEnabled(true); webView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView webView, String url) { if (url.endsWith(".pdf")) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.parse(url), "application/pdf"); /* Check if there is any application capable to process PDF file. */ if (intent.resolveActivity(getPackageManager()) != null) { startActivity(intent); } else { /* If not, show PDF in Google Docs instead. */ view.loadUrl(googleDocs + url); } } else { webView.loadUrl(url); } return true; } });
You may need to change the context transfer and access the startActivity
method, but other than that it should work as it is.
Also note that with API 24 there are 2 shouldOverrideUrlLoading
methods that you can override. As pointed out here from @CommonsWare, it is ok to override the deprecated method.
source share