简体   繁体   English

在Android WebView中使用缓存

[英]Using caching in Android WebView

I have been searching for days for a good caching solution for my WebView app. 我一直在寻找针对我的WebView应用程序的良好缓存解决方案的日子。 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. 本质上,我拥有的是一个大型WebView,底部导航上有一排按钮,用于更改WebView的URL。 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?). 这应该是WebView的默认行为,但是似乎加载速度不是很快(应该马上就可以了吗?)。 I would also like the WebView to load from the cache if the network is unavailable. 如果网络不可用,我还希望WebView从缓存中加载。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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