Handling ‘mailto’ and ‘tel’ Links inside Android WebView

Overview

Previously
we created wrappers around mailto and tel HTML links. Today we
will see how to integrate those wrappers into our Android app to respond to
user clicking mailto and tel links.

Introduction

By inspecting WebView class you can find that there’s no direct
way to subscribe to events of user clicking a link or navigating to another
area of the website. The only way available is through implementing a custom WebViewClient.
The WebViewClient class allows you to take control of various aspects of
WebView like page loading, scale changing, error handling, and many
others. This class is very useful so you got to inspect it yourself. Here we
will focus only on handling page loading event.

mailto and tel Code Listing

For your reference, here’s the full code listing for mailto and tel web links:

ShouldOverrideUrlLoading would
return true if you want to handle the loading events of the requested
URL.

As an object-oriented
approach, we created some events to notify the host activity of the various events
happen inside the WebView. We also implemented two versions of EventArgs
to hold the state data for the events. The code for the EventArgs is displayed
next.

Before notifying the
user of mailto and tel, we ensured first that they have the right
format by calling CanHandle of both classes.

State
Data

Now we would implement the EventArgs classes that would be passed to the host activity. The implementation is very straightforward.

In the previous code, we handled MailRequested and TelephoneRequested
events and passed the data received to the IntentHelper class that we
are going to create next.

Notice that Java.Lang.SecurityException will be
thrown if the application is trying to make a phone call while not permitted.
This should be handled to avoid app crashes.

Sending Emails

The code for sending an email is fairly easy. Next code will request the Android OS to open the mail app and display the relevant information. The OS might ask the user to select an app to handle this request.

Conclusion

The WebViewClient opens the possibility of handling
many aspects and behaviour of WebView. An idea, which we will see in a
future post, is handling the browsing history and allowing the user to go back
and forth. If you have and feedback, comments, or code updates please let me
know.