我的应用程序中有很多 webViews,并希望将它们缓存在设备上。现在我将内容作为字符串保存在 SQLite 数据库中,如果没有互联网连接,我会从那里加载文本。但是如果有人清理设备上的缓存,图片和 css 就不再存在了。
有没有一种简单的方法来缓存页面上链接的所有图片和css?
css 的链接在我缓存的字符串中,因此我必须在保存之前操作此链接?但是怎么做?那么图片呢?
public class MainActivity extends Activity
{
public WebView webView;
public Activity activity;
public Context context;
public String htmlData;
@Override
protected void onCreate(Bundle savedInstanceState)
{
activity = this;
context = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webview);
if (isOnline())
{
new CacheData().execute("");
} else
{
WebCacheDataHandler wcdh = new WebCacheDataHandler(context);
wcdh.open();
String cache = wcdh.getContent();
wcdh.close();
webView.loadData(cache, "text/html", "UTF-8");
}
}
public String getUrlContent(String url) throws IOException
{
URL oracle = new URL(url);
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine;
StringBuilder sb = new StringBuilder();
while ((inputLine = in.readLine()) != null)
{
sb.append(inputLine + "\n");
}
return sb.toString();
}
public boolean isOnline()
{
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting())
{
return true;
}
return false;
}
public class CacheData extends AsyncTask<String, Void, Boolean>
{
@Override
protected Boolean doInBackground(String... string)
{
try
{
htmlData = getUrlContent("http://www.dumdidum.de/");
} catch (IOException e)
{
e.printStackTrace();
}
return true;
}
@Override
protected void onPostExecute(Boolean isModified)
{
webView.loadData(htmlData, "text/html", "UTF-8");
// write data in Database
WebCacheDataHandler wcdh = new WebCacheDataHandler(context);
wcdh.open();
wcdh.insertCache(htmlData);
wcdh.close();
}
}
}
但我不想使用 AppCache/Manifest ;)