I'm building a basic web browser with the android webview component and recently added support for opening links in relevant external apps e.g. if you're on a page and click a youtube link, the youtube app is opened instead of navigating to the web page.
This works fine accept for when an app is freshly installed and you click on a link for the first time (I suspect my app isn't the default browser at this point). Then it always prompts if you want to open it in another app, even if the only other relevant apps are other browsers, which isn't a great user experience as the user is already in the browser they want to open the link in otherwise they wouldn't be using it.
So I need to be able to distinguish between a link that has a dedicated installed app (e.g. it's found a wikipedia app for wikipedia links) vs a link that there are no dedicated apps for and is suitable for any browser to open.
Here's the relevant code in MyWebViewClient.shouldOverrideUrlLoading()
...
Intent intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
if(intent!=null){
PackageManager packageManager = context.getPackageManager();
ResolveInfo info = packageManager.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
if (info != null) {
String suggestedPackageName = info.activityInfo.applicationInfo.packageName;
String intentAction = intent.getAction();
final boolean packageMatchesThisBrowser = (MY_PACKAGE_NAME).equals(suggestedPackageName);
final boolean isUrlAttempt = UrlHelper.isUrlAttempt(url);
final boolean areSuggestedAppsOnlyBrowsers = false; // ????
final boolean canItBeOpenedInThisBrowser = isUrlAttempt;
if(canItBeOpenedInThisBrowser && (packageMatchesThisBrowser || areSuggestedAppsOnlyBrowsers)){
return false; // allow the url to load normally in the current web view
}else {
// Else we have a dedicated app link (e.g. tel://, whatsapp://, intent://) or app supported links like (e.g. https://youtube.com/...)
context.startActivity(intent);
return true; // Launched the activity successfully so block webview from loading
}
} else {
// ...
}
}