如何解决处理 android webview 中的 URI 以打开应用程序或重定向到 Playstore 始终显示 ERR_UNKNOWN_URL_SCHEME
我在我的应用中添加了一个网页视图来管理一些网页。其中一些可能包含指向应用程序的链接。但我收到错误 ERR_UNKNowN_URL_SCHEME。
有时 URL 方案会是 intent:// 或 market:// 等。那么如何在 webview 中正确处理?
我尝试拦截请求
binding.webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view,String url) {
enableui();
}
@Override
public boolean shouldOverrideUrlLoading(WebView view,WebResourceRequest request) {
String url = request.getUrl().toString();
if (url.isEmpty()) {
showMessage(R.string.something_wrong);
} else {
if (URLUtil.isNetworkUrl(url)) {
return false;
} else {
try {
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse(url));
startActivity(intent);
} catch (ActivityNotFoundException ex) {
showMessage(getString(R.string.app_not_found));
}
}
}
finish();
return true;
}
}
);
但是上面的代码总是捕捉到ActivityNotFoundException。 以下是触发错误的示例链接
intent://play.app.goo.gl/?link=https://play.google.com/store/apps/details?id%3Dcom.dreamplug.androidapp#Intent;package=com.google。 android.gms;scheme=https;S.browser_fallback_url=https://play.google.com/store/apps/details%3Fid%3Dcom.dreamplug.androidapp;end;
如果我从 chrome 浏览器尝试,上面的链接可以打开我的 Playstore 应用程序。我想知道为什么我的 webview 不能达到同样的效果。
解决方法
首先,查看网址。 Url 以 intent://
开头,而不是以 http 或 https 开头,因此它是一个 UNKNOWN_URL_SCHEME。这些情况必须分开处理。
为了解决这个问题,您可以在 try-catch 块中添加一个 if
,如下所示。
@Override
public boolean shouldOverrideUrlLoading(WebView view,WebResourceRequest request) {
String url = request.getUrl().toString();
if (url.isEmpty()) {
showMessage(R.string.something_wrong);
} else {
if (URLUtil.isNetworkUrl(url)) {
return false;
} else {
try {
if(url.startsWith("intent")){
// fetching the part that starts with http // https
int startIndex,endIndex;
startIndex=url.indexOf("=")+1;
endIndex=url.indexOf("#");
url=url.substring(startIndex,endIndex); // this url will open the playStore but wait !
// the url we formed still contains some problem at "details?id%3Dcom" bcoz it must be "details?id=com"
url=url.replace("%3D","=");
}
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse(url));
startActivity(intent);
} catch (ActivityNotFoundException ex) {
showMessage(getString(R.string.app_not_found));
}
}
}
finish();
return true;
}
这完全正常,acc。你的问题。但是,它可以根据 url 的形成而有所不同。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。