mailto: links unsupported in Android?
Asked Answered
X

2

9

I dont have a real Android device so I'm using emulators for all my development for now, are mailto: web links really unsupported on Android devices 2.1 and below? 2.2 works, but every time I click a mailto: link on 1.6 or 2.1 even, I get an [unsupported action] dialog. Anybody with a real device want to test this out?

Xenocryst answered 8/9, 2010 at 19:39 Comment(2)
Mailto links where? In a WebView?Palladian
in the mobile browser using 10.0.2.2 to get to localhost.Xenocryst
S
35

You have to handle it yourself in a WebViewClient

public class MyWebViewClient extends WebViewClient {
    Activity mContext;
    public MyWebViewClient(Activity context){
        this.mContext = context;
    }
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {     
        if(url.startsWith("mailto:")){
            MailTo mt = MailTo.parse(url);
            Intent i = new Intent(Intent.ACTION_SEND);
            i.setType("text/plain");
            i.putExtra(Intent.EXTRA_EMAIL, new String[]{mt.getTo()});
            i.putExtra(Intent.EXTRA_SUBJECT, mt.getSubject());
            i.putExtra(Intent.EXTRA_CC, mt.getCc());
            i.putExtra(Intent.EXTRA_TEXT, mt.getBody());
            mContext.startActivity(i);
            view.reload();
            return true;
        }
        view.loadUrl(url);
        return true;
    }
}

In your activity you keep a reference to MyWebViewClient and assign it to your webview with setWebViewClient(mWebClient).

Seiler answered 8/9, 2010 at 20:46 Comment(1)
A minor caveat regarding this solution: the method always returns true, which tells the WebView that "our implementation of WebViewClient handles everything" - this can create problems for edge cases of redirections, such as using location.replace() in JavaScript. Instead of view.loadUrl(url); return true; you can type return false; to achieve the same effect without introducting bugs. See my longer explanation in this answer to another questionSoule
C
2

A simpler way would be:

if(url.startsWith("mailto:")){
    Intent intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
    view.getContext().startActivity(intent);
}
Compunction answered 18/9, 2012 at 13:56 Comment(2)
if (MailTo.isMailTo(url)) { //...Skyjack
I believe Intent.parseUri throws a URISyntaxException so you need to handle with a try { ... } catch { ... }Luminiferous

© 2022 - 2024 — McMap. All rights reserved.