WebView Cache не сохраняет кеш - PullRequest
0 голосов
/ 11 марта 2019

Я пытаюсь кэшировать WebView, но он не работает. В частности, когда я выключаю фрагмент с помощью WebView, выключаю WiFi и возвращаюсь к фрагменту, он выдает мне ошибку: net :: ERR_CACHE_MISS, когда я проверяю сеть и LOAD_CACHE_ONLY. Когда я устанавливаю значение LOAD_CACHE_ELSE_NETWORK без проверки сетевого подключения и выключаю WiFi после загрузки, я получаю пустой белый экран, даже когда WiFi включен.

До ссылки на другие темы я уже использовал this и несколько других

Вот мой код

Класс, управляющий фрагментом с помощью WebView:

import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.net.ConnectivityManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import static android.content.Context.CONNECTIVITY_SERVICE;

public class CalendarFragment extends Fragment {
    private WebView webView;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view =  inflater.inflate(R.layout.calendar_layout, container, false);
        webView = (WebView) view.findViewById(R.id.calendarWebView);
        webView.getSettings().setAppCacheMaxSize( 8 * 1024 * 1024 );
        webView.getSettings().setAppCacheEnabled(true);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setAppCachePath(getContext().getCacheDir().getPath());
        webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        webView.setWebViewClient(new WebViewClient());
        if ( !isNetworkAvailable() )  //offline
            //webView.getSettings().setCacheMode( WebSettings.LOAD_CACHE_ONLY );
        webView.loadUrl("https://calendar.google.com/calendar/htmlembed?src=wlmacci%40gmail.com&ctz=America%2FToronto");
        //webView.loadUrl("https://sites.google.com/view/wlmac/textfile?");
        //webView.loadUrl("https://google.ca");
        //webView.getSettings().setLoadWithOverviewMode(true);
        //webView.getSettings().setUseWideViewPort(true);
        return view;
    }
    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getContext().getSystemService( CONNECTIVITY_SERVICE );
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }
}

Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.starenkysoftware.macapp">
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:usesCleartextTraffic="true">

        <activity
            android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Макет с WebView в нем:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="@android:color/holo_red_light">


    <TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="Calendar Fragment"
    android:textSize="30sp"
    android:gravity="center"
    android:layout_centerInParent="true"/>

    <WebView
        android:id="@+id/calendarWebView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="fitXY"
        android:visibility="visible"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

    </WebView>

</RelativeLayout>

Я предоставлю любые другие необходимые ресурсы / код по запросу. Любая помощь приветствуется.

...