且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Webview电子邮件链接(mailto)

更新时间:2023-11-26 18:46:22

您必须创建WebViewClient的子类并覆盖mailto URL加载.示例:

You have to create a subclass of WebViewClient and override mailto URL loading. Example:

public class MyWebViewClient extends WebViewClient {
  private final WeakReference<Activity> mActivityRef;

  public MyWebViewClient(Activity activity) {
    mActivityRef = new WeakReference<Activity>(activity);
  }

  @Override
  public boolean shouldOverrideUrlLoading(WebView view, String url) {
    if (url.startsWith("mailto:")) {
      final Activity activity = mActivityRef.get();
      if (activity != null) {
        MailTo mt = MailTo.parse(url);
        Intent i = newEmailIntent(activity, mt.getTo(), mt.getSubject(), mt.getBody(), mt.getCc());
        activity.startActivity(i);
        view.reload();
        return true;
      }
    } else {
      view.loadUrl(url);
    }
    return true;
  }

  private 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;
  }
}

然后,您必须将此自定义WebViewClient设置为WabView:

Then you have to set this custom WebViewClient to your WabView:

webView.setWebViewClient(new MyWebViewClient(activity);