将css保存在设备上以在离线模式下加载它

时间:2013-04-11 12:40:02

标签: android css caching webview offline

我的应用中有很多webView,想要将它们缓存在设备上。现在我将内容保存为SQLite数据库中的字符串,如果没有Internet连接,我从那里加载文本。但如果有人清理设备上的缓存,则图片和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;)

0 个答案:

没有答案