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測試時直接掛掉了。

相關文章
相關標籤/搜索