Reputation: 184
I added a web view to my app to manage some web pages. Some of them may contain links to applications. But I got an error ERR_UNKNOWN_URL_SCHEME.
Sometimes the URL schemes will be intent:// or market:// etc. So how to handle this properly in webview?
I tried intercepting the request
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;
}
}
);
But the above code always catches ActivityNotFoundException. Following is a sample link that triggers the error
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;
If I try from the chrome-browser the above link is able to open my playstore app. I wonder why I can't achieve the same with my webview.
Upvotes: 1
Views: 2594
Reputation: 768
Firstly, look at the url. The Url is starting with intent://
and not with http or https therefore it's an UNKNOWN_URL_SCHEME. These cases must be handled separately.
For rectifying this, you can add an if
in try-catch block like below.
@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;
}
This works completely fine acc. to your question. But, it can vary according to the formation of url.
Upvotes: 3