简体   繁体   中英

WebView, link to Google Photos album but ERR_UNKNOWN_URL_SCHEME

I'm developing a simple WebView app on Android with two tabs , one shows the website and the second one reads an XML File to output all the recent news.

In one of these articles there's a Google Photo's album link but when I click it shows the error in the image. I don't understand why it doesn't simply load the link.

Incidentally, I also tried to read the Google docs about "Intent", "DeepLink" because I'd like to open the link with the pre-installed app 'Photos' and let the users watch the album directly from the official Photos app.

ERR_UNKNOWN_URL_SCHEME

this is my MainActivity.java

  package com.example.matte.parrocchiasanbenedetto;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.annotation.IntDef;
import android.support.design.widget.TabLayout;
import android.support.design.widget.TabLayout.Tab;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.webkit.URLUtil;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    //private ConstraintLayout container;
    public TabLayout tabLayout;
    public WebView myWebView;
    public SwipeRefreshLayout mySwipeRefreshLayout;
    //public TextView myTxtView;
    private Tab[] tabItem;
    final int[] ICONS = new int[]{
            R.drawable.ic_church,
            R.drawable.ic_feed
    };
    private String[] url;
    private static final int WEBSITE = 0, FEED = 1;
    @IntDef({WEBSITE, FEED})
    @Retention(RetentionPolicy.SOURCE)
    public @interface Operation {}


    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        url = new String[]{getString(R.string.url0), getString(R.string.url1)};

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        tabLayout = findViewById(R.id.tabs);
        mySwipeRefreshLayout = findViewById(R.id.swiperefresh);

        myWebView = findViewById(R.id.webView);
        myWebView.getSettings().setBuiltInZoomControls(true);
        myWebView.getSettings().setDisplayZoomControls(false);
        myWebView.getSettings().setLoadWithOverviewMode(true);
        myWebView.getSettings().setUseWideViewPort(true);
        myWebView.setPadding(0, 0, 0, 0);
        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        //myWebView.setWebViewClient(new WebViewClient());
        myWebView.setWebChromeClient(new WebChromeClient(){

        });

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(Tab tab) {
                switch (tabLayout.getSelectedTabPosition()) {
                    case WEBSITE: {
                        myWebView.loadUrl(url[tabLayout.getSelectedTabPosition()]);
                        break;
                    }
                    case FEED: {
                        try {
                            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                            StrictMode.setThreadPolicy(policy);
                            readFeed();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        break;
                    }
                }
            }

            @Override
            public void onTabUnselected(Tab tab) {
            }

            @Override
            public void onTabReselected(Tab tab) {

            }
        });

        mySwipeRefreshLayout.setOnRefreshListener(
                new SwipeRefreshLayout.OnRefreshListener() {
                    @Override
                    public void onRefresh() {
                        myUpdateOperation();
                    }
                }
        );

        fillTabItem();
        myWebView.setWebViewClient(new WebViewClient());
        myWebView.loadUrl(url[tabLayout.getSelectedTabPosition()]);
    }

    private void fillTabItem() {
        tabItem = new Tab[tabLayout.getTabCount()];
        for(int i=0; i<tabLayout.getTabCount(); i++) {
            tabItem[i] = tabLayout.getTabAt(i);
            tabLayout.getTabAt(i).setIcon(ICONS[i]);
        }
    }

    private void readFeed() throws IOException {
        XmlPullParserFactory parserFactory;
        URL webUrl = new URL(url[1]);
        try {
            parserFactory = XmlPullParserFactory.newInstance();
            XmlPullParser parser = parserFactory.newPullParser();
            InputStream is = webUrl.openStream();
            parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
            parser.setInput(is, null);
            myWebView.loadDataWithBaseURL(null, processParsing(parser), "text/HTML", "UTF-8", null);
        } catch (XmlPullParserException e) {

        } catch (IOException e) {

        }
    }

    @Override
    public void onBackPressed() {
        if (this.myWebView.canGoBack()) {
            this.myWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }

    public void openWebPage(String url) {
        Uri webpage = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW, webpage);
        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivity(intent);
        }
    }

    public void myUpdateOperation() {
        this.myWebView.reload();
        this.mySwipeRefreshLayout.setRefreshing(false);
    }

    private String processParsing(XmlPullParser parser) throws IOException, XmlPullParserException {
        ArrayList<XMLParser.Feed> feeds = new ArrayList<>();
        int eventType = parser.getEventType();
        XMLParser.Feed currentFeed = null;

        while(eventType != XmlPullParser.END_DOCUMENT) {
            String eltName = null;
            switch(eventType) {
                case XmlPullParser.START_TAG: {
                    eltName = parser.getName();
                    if ("item".equals(eltName)) {
                        currentFeed = new XMLParser.Feed();
                    } else if (currentFeed != null) {
                        if("title".equals(eltName)) {
                            currentFeed.setTitle(parser.nextText());
                        /*} else if ("comments".equals(eltName)) {
                            currentFeed.setComments(parser.nextText());
                        } else if ("pubDate".equals(eltName)) {
                            currentFeed.setPubDate(parser.nextText());
                        } else if ("dc:creator".equals(eltName)) {
                            currentFeed.setCreator(parser.nextText());
                        } else if ("description".equals(eltName)) {
                            currentFeed.setDescription(parser.nextText());*/
                        } else if ("content:encoded".equals(eltName)) {
                            String str = parser.nextText().replaceAll("<a href=", "<a href='#' ");
                            //str.replaceAll("https", "http");
                            currentFeed.setContent(str);
                            //currentFeed.setContent(parser.nextText());
                        }
                    }
                    break;
                }
                case XmlPullParser.END_TAG: {
                    eltName = parser.getName();
                    if ("item".equalsIgnoreCase(eltName)) {
                        feeds.add(currentFeed);
                    }
                }
            }
            eventType = parser.next();
        }
        return printFeed(feeds);
    }

    private String printFeed(ArrayList<XMLParser.Feed> feeds) {
        StringBuilder builder = new StringBuilder();
        builder.append("<html>").
                append("<head><style> body {font-size: 150%;} img {display: block; margin: 0 auto;} </style></head>").
                //append("<head><style> img {display: block; margin: 0 auto; width: 50%; height: 30%;} </style></head>").
                append("<body>").
                append("<p>");

        for(XMLParser.Feed feed : feeds) {
            builder.append("<h1>").
                    append(feed.getTitle()).
                    append("</h1><br>").
                    append(feed.getContent()).append("<br>");
            builder.append("<hr size='1'").append("<p style='line-height: 18px;'></p>");
        }
        builder.append("</p>").
                append("</body>").
                append("</html>");

        return builder.toString();
    }

}

this is my AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.matte.parrocchiasanbenedetto">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/fazzolettino"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/fazzolettino"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:configChanges="orientation|screenSize"

            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <intent-filter android:autoVerify="true">
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data
                    android:host="photos.app.goo.gl"
                    android:scheme="https" />


            </intent-filter>
        </activity>
    </application>

</manifest>

I think what's happening is that Google's site is detecting the device has the Google Photos app installed and tries launch that app using and intent, but the webview doesn't know how to deal with the intent:// scheme. What you could do is try to launch the activity yourself, instead of loading the url to your webview:

        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        boolean canOpen = browserIntent.resolveActivity(getPackageManager()) != null;
        if (canOpen) {
            startActivity(browserIntent);
        } else {
            webview.loadUrl(url);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM