您的位置:首页 > 移动开发

WebView清除缓存的有效方法

2012-02-29 10:58 429 查看
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="webLoad" 
        android:id="@+id/loadId"
        />
     <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="clearCache" 
          android:id="@+id/clearId"
        />
    
      <WebView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/webViewId"
        
         />
</LinearLayout>


public class WebCacheActivity extends Activity implements OnClickListener {
    private Button clearBtn, loadBtn;
    private WebView webView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        clearBtn = (Button) findViewById(R.id.clearId);
        loadBtn = (Button) findViewById(R.id.loadId);

        clearBtn.setOnClickListener(this);
        loadBtn.setOnClickListener(this);
        webView = (WebView) findViewById(R.id.webViewId);
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        WebSettings webSettings = webView.getSettings();       
        webSettings.setJavaScriptEnabled(true);  
        
        webView.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

        });
        webView.loadUrl("http://www.baidu.com/");
        
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.clearId://清除缓存的有效方法
            webView.loadDataWithBaseURL(null, "","text/html", "utf-8",null);
            break;
        case R.id.loadId:
            webView.loadUrl("http://www.baidu.com/");
            break;
        default:
            break;
        }
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: