I have my WebView
loading all links inside the webview - but when I select an email link it tries to load it in the webview instead of launching an email app on
::::
::::
webViewTerms = (WebView) v
.findViewById(R.id.webview_termsAndCond);
webViewTerms.setWebViewClient(new Client());
webViewTerms.getSettings().setJavaScriptEnabled(true);
//webViewTerms.getSettings().setBuiltInZoomControls(true);
webViewTerms.loadUrl(getUrl()); //.loadUrl("https://www.google.com/");
::::
::::
::::
private class Client extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
@Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
}
}
Going off of the answer provided by @schwiz, here is a cleaner example. Assuming the WebView
is named webView
:
webView.setWebViewClient(new WebViewClient() {
// shouldOverrideUrlLoading makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// Use an external email program if the link begins with "mailto:".
if (url.startsWith("mailto:")) {
// We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
// Parse the url and set it as the data for the `Intent`.
emailIntent.setData(Uri.parse(url));
// `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of this application.
emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Make it so.
startActivity(emailIntent);
return true;
} else {
// Returning false causes WebView to load the URL while preventing it from adding URL redirects to the WebView history.
return false;
}
}
});
I have tested this with all the mailto:
options: multiple email addresses, CC, BCC, subject, and body.
I assume you are already overriding shouldOverrideUrlLoading, you just need to handle this special case.
mWebClient = new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(url.startsWith("mailto:")){
MailTo mt = MailTo.parse(url);
Intent i = newEmailIntent(MyActivity.this, mt.getTo(), mt.getSubject(), mt.getBody(), mt.getCc());
startActivity(i);
view.reload();
return true;
}
else{
view.loadUrl(url);
}
return true;
}
};
mWebView.setWebViewClient(mWebClient);
public static Intent newEmailIntent(Context context, String address, String subject, String body, String cc) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_EMAIL, new String[] { address });
intent.putExtra(Intent.EXTRA_TEXT, body);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_CC, cc);
intent.setType("message/rfc822");
return intent;
}