webView缓存无法使用loadDataWithBaseURL()

时间:2014-02-08 14:51:39

标签: android caching webview

我在我的应用中将一些html字符串加载到webview中。我的代码:

public class AboutUsFragment extends SherlockFragment {
    String url = CommonUtils.aboutUsUrl;
    private FetchTask fetchTask = null;
    WebView webView = null;
    @SuppressLint("SetJavaScriptEnabled")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.wrapper, container, false);
        webView = (WebView) rootView.findViewById(R.id.wrapper);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setAppCacheMaxSize(5 * 1024 * 1024); // 5MB
        webView.getSettings().setAppCachePath(
                getSherlockActivity().getCacheDir().getAbsolutePath());
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setAppCacheEnabled(true);
        return rootView;
    }
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // check whether internet connection is available or not
        ConnectionDetector cd = new ConnectionDetector(getSherlockActivity());
        boolean hasConnection = cd.isConnectingToInternet();
        if(hasConnection) {
            webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
            fetchTask = new FetchTask();
            fetchTask.execute();
        } else {
            MainActivity.networkAvailabilityNotice(getSherlockActivity());
            webView.getSettings().setCacheMode(
                    WebSettings.LOAD_CACHE_ELSE_NETWORK);
        }
    }

    protected class FetchTask extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {
            // data fetching from JSON feed
            return data;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            webView.loadDataWithBaseURL("", result, "text/html", "UTF-8", "");
        }

    }
}

问题在于 - 缓存无法正常工作,即网页未在离线模式下显示。我设法使用loadURL()方法提供过去的缓存。如何使用loadDataWithBaseURL()在离线模式下提供webview缓存?

1 个答案:

答案 0 :(得分:0)

好吧,我没有找到任何内置方法来缓存内容,就像典型的webview一样。所以我将文本保存在.txt文件中,并在离线模式下读取该内容。 :)