Webview email link (mailto)

前端 未结 3 767
暖寄归人
暖寄归人 2021-01-31 15:39

I have a view and view the site has malito code to send email. When I open the link opens in an error. I want that when I open the link opens Gmail app or another email applic

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-31 16:15

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

    public class MyWebViewClient extends WebViewClient {
      private final WeakReference mActivityRef;
    
      public MyWebViewClient(Activity activity) {
        mActivityRef = new WeakReference(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;
      }
    }
    

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

    webView.setWebViewClient(new MyWebViewClient(activity);
    

提交回复
热议问题