Issue
In my android app, I have a WebView. I want every link click within my WebView to launch the registered app on my device, if any, otherwise open in an external browser. For example, if a user clicks on a Facebook page link from within the WebView, it should launch the Facebook app (if facebook is registered on the device to handle facebook links). If no app is registered, it should launch the external browser (i.e, it should not load the page in the same WebView).
Currently (by default), the WebView just loads any link clicked within the WebView within itself.
I realize I need to override shouldOverrideUrlLoading to intercept those link clicks:
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// what should go here to trigger the registered app or fall back to external browser for all link clicks in the WebView?
}
});
I also looked at intent filters, but that seems to be the inverse of this requirement (intent filters seem to be a way for me to register my android app to handle web clicks elsewhere).
Update 1:
I am not looking to intercept any particular host name or scheme - I want every link that is clicked in my web view to be 'delegated' to android, where android decides whether to launch a registered app, pop up a choice for user to pick which app to open in, or open in web browser, depending on user settings.
Specifically, if I click on a link to https://www.facebook.com/blah it should launch in the facebook app and take me to the blah page there.
Solution
The fix simply involved handling shouldOverrideUrlLoading to true, and if the url isn't within my own app, returning true. When true is returned, it launches registered app or app chooser dialog or browser, depending on the configured context.
mWebview.setWebViewClient(new WebViewClient()
{
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
boolean isLocalUrl = false;
try {
URL givenUrl = new URL(url);
String host = givenUrl.getHost();
if(host.contains("myapp.com"))
isLocalUrl = true;
} catch (MalformedURLException e) {
}
if (isLocalUrl)
return super.shouldOverrideUrlLoading(view, url);
else
{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
});
I also realized that the current status on Android (I tested on MIUI 7 on Xiaomi Mi 4, based on Android Kitkat, but forums indicate that this is broadly true for most pre-Marshmallow androids at least) where a link to a facebook page in the WebView does not open in the Facebook app. Nor does it give user the option to open in Facebook app. This used to work earlier, but does not work now. It always launches in the browser if we use the above code. A lot of the misunderstanding happened because of this. It works as expected with other sites (twitter, quora, etc.).
Answered By - Anand
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.