1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
| package com.cfsuman.me.androidcodesnippets;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Context mContext;
private Activity mActivity;
private WebView mWebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get the application context
mContext = getApplicationContext();
mActivity = MainActivity.this;
// Get the widget reference from xml layout
mWebView = findViewById(R.id.web_view);
// Set the web view client
mWebView.setWebViewClient(new WebViewClient(){
// For api level bellow 24
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
Toast.makeText(mContext, "Old Method",Toast.LENGTH_SHORT).show();
if(url.startsWith("http")){
Toast.makeText(mContext,"Page link",Toast.LENGTH_SHORT).show();
// Return false means, web view will handle the link
return false;
}else if(url.startsWith("tel:")){
// Handle the tel: link
handleTelLink(url);
// Return true means, leave the current web view and handle the url itself
return true;
}
return false;
}
// From api level 24
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request){
Toast.makeText(mContext, "New Method",Toast.LENGTH_SHORT).show();
// Get the tel: url
String url = request.getUrl().toString();
if(url.startsWith("http")){
Toast.makeText(mContext,"Page link",Toast.LENGTH_SHORT).show();
// Return false means, web view will handle the link
return false;
}else if(url.startsWith("tel:")){
// Handle the tel: link
handleTelLink(url);
// Return true means, leave the current web view and handle the url itself
return true;
}
return false;
}
});
// Load the url into web view
//mWebView.loadUrl("https://paulund.co.uk/add-telephone-number-links-with-html5");
mWebView.loadUrl("https://developers.google.com/web/fundamentals/native-hardware/click-to-call/");
}
// Custom method to handle html tel: link
protected void handleTelLink(String url){
// Initialize an intent to open dialer app with specified phone number
// It open the dialer app and allow user to call the number manually
Intent intent = new Intent(Intent.ACTION_DIAL);
// Send phone number to intent as data
intent.setData(Uri.parse(url));
// Start the dialer app activity with number
startActivity(intent);
}
} |
Partager