在 Android WebView 中使用缓存



我已经为我的 WebView 应用程序寻找了一个好的缓存解决方案。我找到的解决方案似乎对我不起作用。我是制作应用程序的新手,以及对弃用许多旧解决方案的缓存更改似乎阻碍了我。

从本质上讲,我拥有的是一个大的 WebView,底部导航上有一排按钮,用于更改 WebView 的 URL。我希望之前已经加载的页面从缓存中加载。这应该是 WebView 的默认行为,但它似乎加载速度并不快(它应该几乎是即时的,对吧?我还希望在网络不可用时从缓存加载 WebView。

这是我到目前为止删除了之前缓存尝试的代码片段。

@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;
}
};

添加此行以在 webview 中加载 javascript。

my_web_view.getSettings().setDomStorageEnabled(true);

最新更新