Android Webview仅每隔一次从缓存加载图像

时间:2016-10-08 07:53:36

标签: android image webview

下面是我的代码,如果没有互联网连接,我想从缓存中加载网页,但是当没有连接时,页面首次加载没有图像,然后当我再次尝试加载时,下次它没有加载图片。就像它的工作时间一样好。

public class school extends Fragment {
private WebView webView;
public Main2Activity main2activity;
public static school newInstance() {
    return new school();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_school, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
        webView = (WebView)
                getView().findViewById(R.id.mywebview);
    main2activity = (Main2Activity) getActivity();

    String url=getResources().getString(R.string.urlSchool);
    //String postData = "schoolId="+main2activity.txtschoolId+"&phoneNumber="+main2activity.txtphoneNumber+"&password="+main2activity.txtpassword;
    startWebView(url);
}
public void startWebView(final String url) {
    int state=0;
    ConnectivityManager connMgr = (ConnectivityManager)
            getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isConnected()) {
        state=1;
    } else {
        state=0;
    }
    webView.setWebViewClient(new WebViewClient() {
        ProgressDialog progressDialog;
        public void onLoadResource (WebView view, String url) {
            if (progressDialog == null) {
                progressDialog = new ProgressDialog(getActivity());
                progressDialog.setMessage("Loading...");
                progressDialog.show();
            }
        }
        public void onPageFinished(WebView view, String url) {
            progressDialog.dismiss();
        }
    });

    if(state==1) {
        webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
    }
    else{
        webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ONLY);
    }
    webView.post(new Runnable() {
        @Override
        public void run() {
            webView.loadUrl(url);
        }
    });
}

}

0 个答案:

没有答案