简体   繁体   中英

Using caching in Android WebView

I have been searching for days for a good caching solution for my WebView app. The solutions I find don't seem to work for me. Me being new at making apps along with the changes on caching that deprecates many older solutions seems to be hampering me.

Essentially, what I have is a large WebView with a row of buttons on the bottom navigation changing the URL of the WebView. I would like pages that were already loaded previously to load from cache. This should be the default behavior of the WebView, but it doesn't seem to be loading faster (it should be almost instant right?). I would also like the WebView to load from the cache if the network is unavailable.

This is a snippet of the code I have so far with my previous attempts at caching removed.

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

    BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
    navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);

    my_web_view = (WebView)findViewById(R.id.web_view); //grab a handle on the web wrapper

    //set all of our variables for use later
    home_URL = "https://akvcoc.com/app-home";
    events_URL = "https://akvcoc.com/app-events";
    directory_URL = "https://akvcoc.ctrn.co/directory/index.php";

    my_web_view.loadUrl(home_URL);                    //set the web wrapper to the home page

    my_web_view.getSettings().setJavaScriptEnabled(true);              //and set javascript to true

}

private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
        = new BottomNavigationView.OnNavigationItemSelectedListener()
{

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item)
    {
        switch (item.getItemId())
        {
            case R.id.navigation_home:
                my_web_view.loadUrl(home_URL);
                return true;
            case R.id.navigation_events:
                my_web_view.loadUrl(events_URL);
                return true;
            case R.id.navigation_directory:
                my_web_view.loadUrl(directory_URL);
                return true;
        }
        return false;
    }
};

您添加此行以将JavaScript加载到Webview中。

my_web_view.getSettings().setDomStorageEnabled(true);

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