Friday, January 25, 2013

Android: Invoking a URL Scheme Intent from a WebView

A few days back, I was working on a project where one of our PhoneGap Android apps needed to invoke another application using the custom URI scheme.

We were able to invoke the other app, when clicking on a link from the mobile browser, but the same did not work from our app.

We figured out that the issue was with the Webview as it was not able to recognize the custom URI.

Solution: After a lot of research, I was able to get to a fix.

The Android Webview component allows using a WebView client. The Webview client exposes a method and I just overrided it as follows: public boolean shouldOverrideUrlLoading(WebView view, String url)
{
                if(url.toLowerCase().startsWith("http") || url.toLowerCase().startsWith("https") || url.toLowerCase().startsWith("file"))
                {
                                view.loadUrl(url);
                }
                else
                {
                                try
                                {
                                                Uri uri = Uri.parse(url);
                                                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                                                                startActivity(intent);
                                }
                                catch (Exception e)
                                {
                                                Log.d("JSLogs", "Webview Error:" + e.getMessage());;
                                }
                }
    return (true);
}

That's it, once you configure the code as above, any URL scheme inside the HTML page would work like a charm. What I simply did was to tell the Webview that if the URL is HTTP, HTTPS or FILE, you handle it, otherwise fire an intent and let the OS handle the same. Simple, yet no one blog has this solution clearly articulated, hence this post.

No comments:

Post a Comment