Android 之 WebView

1:在AndroidManifest.xml中添加容许android访问网络权限。html

<uses-permission android:name="android.permission.INTERNET"/>android

2:activity_main.xmlweb

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">网络

<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>ide

</RelativeLayout>布局

3:MainActivity测试

public class MainActivity extends Activity {
  private WebView webView=null;
  private String url="http://www.baidu.com";
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    webView=(WebView)findViewById(R.id.webView);
    webView.loadUrl(url);

    //设置支持JS or Flash
    WebSettings webSettings=webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setPluginState(WebSettings.PluginState.ON);

    //继续让其余网页显示在WebView中
    webView.setWebViewClient(new WebViewClient(){
      public boolean shouldOverrideUrlLoading(WebView view,String url){
        view.loadUrl(url);
        return true;
      }ui

    });
  }this

}url

4:运行界面以下。

WebView不只能够显示URL网页内容,还能够将服务端传递过来的HTML+CSS片断展示出来例如:

webView.loadDataWithBaseURL(null, str, "text/html", "UTF-8", null);

WebView将assets文件夹下面的html文件展示出来:

webView.loadUrl("file:///android_asset/html/"+index+".html");

 

WebView中常见的错误:

(1):Error

Activity com.wzh.activity.BsznContent has leaked IntentReceiver
com.android.qualcomm.browsermanagement.BrowserManagement$1@4196c878 that was
originally registered here. Are you missing a call to unregisterReceiver()?

 解决方法:不要在XML布局中直接编写WebView的XML布局代码,在代码中编写,将其添加到一个父容器中,例如:

llXxsdWebView = (LinearLayout)findViewById(R.id.llXxsdWebView);
webView = new WebView(getApplicationContext());
llXxsdWebView.addView(webView);

在onDestroy()方法中:将WebView移除,以及WebView中的全部VIew移除,最后将WebView销毁。

protected void onDestroy() {
        super.onDestroy();
        if(null != webView){
            llXxsdWebView.removeAllViews();
            webView.removeAllViews();
            webView.destroy();
        }
    }

(2):Error

Error: WebView.destroy() called while still attached!

参考:http://stackoverflow.com/questions/11995270/error-webview-destroy-called-while-still-attached

相似(1)中的写法:

webViewPlaceholder.removeView(myWebView); myWebView.removeAllViews(); myWebView.destroy();

(3):Warning

skip viewSizeChanged as w is 0

参考:http://stackoverflow.com/questions/5582530/android-what-does-this-warning-message-refer-to-webcore

WebView mWebView =(WebView) findViewById(R.id.webview); mWebView.getSettings().setBuiltInZoomControls(true);

 

总结:对于Android4.0.4在使用 WebView时会出现许多意想不到的问题,相比较Android4.2.2就会好许多。我在Android4.2.2平台上使用WebView,在Logcat下没有报道任何错误异常,而在使用Android4.0.4测试时直接挂掉了。

相关文章
相关标签/搜索