Android WebView加载支付宝Scheme失败?如何正确处理alipays://链接?

Android WebView加载支付宝Scheme失败?如何正确处理alipays://链接?

android webview加载支付宝Scheme失败解决方案

在Android开发中,WebView加载包含自定义URL Scheme(例如支付宝的alipays://)的链接时,常常遇到net::err_unknown_url_scheme错误,导致页面无法正常加载,并在onReceivedError回调中返回错误码-10。即使重写了shouldOverrideUrlLoading方法,问题依然存在。这是因为WebView默认不支持处理自定义URL Scheme。

本文提供有效的解决方案。关键在于正确重写WebViewClient的shouldOverrideUrlLoading方法,并使用Intent启动相应应用处理自定义URL Scheme。

许多开发者尝试重写shouldOverrideUrlLoading方法却未能解决问题,原因可能是方法实现存在缺陷。以下是一个经过验证的正确实现:

首先,为WebView设置WebViewClient:

webView.setWebViewClient(new WebViewClient() {     @Override     public boolean shouldOverrideUrlLoading(WebView view, String url) {         if (url.startsWith("alipays://")) {             // 处理支付宝Scheme             Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));             try {                 startActivity(intent);             } catch (ActivityNotFoundException e) {                 // 处理支付宝客户端未安装的情况                 e.printStackTrace();                 // 可在此处提示用户安装支付宝客户端             }             return true; // 拦截URL,阻止WebView加载         }         // 其他URL,使用WebView默认行为         return super.shouldOverrideUrlLoading(view, url);     }      @Override     public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {         super.onReceivedError(view, errorCode, description, failingUrl);         // 处理加载错误,例如显示错误提示     } });

代码首先检查URL是否以”alipays://”开头。如果是,则创建Intent,使用ACTION_VIEW动作和解析后的URI启动支付宝应用。try-catch块处理支付宝应用未安装的情况,避免程序崩溃。return true表示已处理该URL,WebView无需加载。 如果不是支付宝Scheme,则调用父类的shouldOverrideUrlLoading方法,让WebView处理其他URL。onReceivedError方法用于处理加载错误,开发者可在此添加错误处理逻辑。

通过此方法,即可正确拦截和处理支付宝自定义URL Scheme,解决net::err_unknown_url_scheme错误。

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享