Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Web-View shouldOverrideUrlLoading() Deprecated.(Alternative)

I have Found a method to make mailto work in android webview but the method is deprecated.Can any one give me full code snippet of the new method. Here is the method I found on this site

Java code is below:

@Override
   public boolean shouldOverrideUrlLoading(WebView view, String url) {

     if (url.startsWith("tel:")) {
         initiateCall(url);
         return true;
      }
       if (url.startsWith("mailto:")) {
         sendEmail(url.substring(7));
         return true;
      }
         return false;
  }

But it's not working when I have target platform as Android 7.1.1

like image 721
M Venkat Naidu Avatar asked Feb 01 '17 05:02

M Venkat Naidu


People also ask

What is WebViewClient Android?

Android WebView is a system component for the Android operating system (OS) that allows Android apps to display content from the web directly inside an application.

What is a WebViewClient?

WebViewClient is the object responsible for most the actions inside a WebView. JavaScript enabled, security, routing, etc. You can make a custom one, as well as use a Chrome one.

What is shouldOverrideUrlLoading?

shouldOverrideUrlLoading is called when a new page is about to be opened whereas shouldInterceptRequest is called each time a resource is loaded like a css file, a js file etc.


1 Answers

Android N and above has this method signature:

public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request)

The one that is supported by all Android versions has this method signature:

public boolean shouldOverrideUrlLoading(WebView view, String url)

What should I do to make it work on all versions?

you need to override both the methods

For every api including Android N+ you need to change your code.

Check this below code. It will target both lower API with N and above

@SuppressWarnings("deprecation")
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    if (url.startsWith("tel:")) {
        initiateCall(url);
        return true;
    }
    if (url.startsWith("mailto:")) {
        sendEmail(url.substring(7));
        return true;
    }
    return false;
}

@RequiresApi(Build.VERSION_CODES.N)
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
    String url = request.getUrl().toString();
    if (url.startsWith("tel:")) {
        initiateCall(url);
        return true;
    }
    if (url.startsWith("mailto:")) {
        sendEmail(url.substring(7));
        return true;
    }
    return false;
}
like image 72
Abhishek Singh Avatar answered Sep 21 '22 05:09

Abhishek Singh