简体   繁体   中英

Open phone dialer using a Android Xamarin WebView html link

I'm trying to use the ShouldOverrideUrlLoading() method but the app crashes when I call it.

Below is my code:

private class HybridWebViewClient : WebViewClient
        {


            public override bool ShouldOverrideUrlLoading(WebView webView, string url)
            {

                var tel = "tel:";
                if (url.StartsWith(tel))
                {

                    var uri = Android.Net.Uri.Parse(url);
                    var intent = new Intent(Intent.ActionDial, uri);
                    var act = new Activity();
                    act.StartActivity(intent);
                }

            }
        }

Thanks in Advance!

The problem lies in the following codes snippet:

var act = new Activity();
act.StartActivity(intent);

The method StartActivity should be called from current context instead of a new Activity . So you need to pass the current context to HybridWebViewClient :

public class HybridWebViewClient : WebViewClient
{
    Context context;
    public HybridWebViewClient(Context context)
    {
        this.context = context;
    }

    public override bool ShouldOverrideUrlLoading(WebView view, string url)
    {
        var tel = "tel:";
        if (url != null)
        {
            if (url.StartsWith(tel))
            {

                var uri = Android.Net.Uri.Parse(url);
                var intent = new Intent(Intent.ActionDial, uri);
                context.StartActivity(intent);
            }
        }
        return true;
    }
}

And in the OnCreate method:

protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);
    ...
    webview.SetWebViewClient(new HybridWebViewClient(this));
    webview.LoadUrl("http://example.com");
   ...
}

What is in the craash dump? Is this related?

shouldOverrideUrlLoading(WebView view, String url) This method was deprecated in API level 24. Use shouldOverrideUrlLoading(WebView, WebResourceRequest) instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM