virsir
virsir

Reputation: 15509

Android webview, start ACTION_VIEW activity when the url could not be handled by webview

Actually I know how to start the market app by URL filtering with my custom webview client, but I want to make it more generic, that is to check each URL, not only the market url, but also some other url protocol that the webview would not know how to deal with it, and start the ACTION_VIEW intent to handle that.

I thought maybe I can check if the url is not started with "http" "https" "ftp" "mailto", if the url is in these protocol, the webview can handle it by itself, for others, I will start a new Intent to try to handle that.

What is your idea? am I correct? any missing protocol that webview could handle?

    webView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url != null && url.contains("://") && url.toLowerCase().startsWith("market:")) {
                try {
                    view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                    return true;
                } catch (Exception ex) {
                }
            }
            view.loadUrl(url);
            return true;
        }
    });

Upvotes: 10

Views: 3716

Answers (1)

kabuko
kabuko

Reputation: 36312

One approach you could try is to take a look at PackageManager.queryIntentActivities(Intent, int). This method gives you info for all of the activities that can handle a given Intent. You could simply create an Intent and see what it returns. If you want to have your WebView take priority when it can handle the URL, you could optionally handle any results which include the browser activity. I haven't tried this code, but it might look something like:

webView.setWebViewClient(new WebViewClient() {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));

        List<ResolveInfo> infos = getPackageManager().queryIntentActivities(intent, 0);

        if (infos.size() == 0) {
            // apparently nothing can handle this URL
            return false;
        }

        for (ResolveInfo info : infos) {
            if (info.activityInfo.packageName.equals("com.android.browser")) {
                view.loadUrl(url);
                return true;
            }
        }

        startActivity(intent);
        return true;
    }
});

Upvotes: 6

Related Questions