Android webview交互

首先要在manifest.main文件中创建一个webview,然后再activity中定义这个webview然后进行一下相关操作。

1、添加权限:AndroidManifest.xml中必须使用许可"android.permission.INTERNET",否则会出Web pagenot available错误。

2、在要Activity中生成一个WebView组件:

[java]  view plain copy
  1. WebView webView = newWebView(this);  

3、设置WebView基本信息:

          如果访问的页面中有Javascript,则webview必须设置支持Javascript。

         webview.getSettings().setJavaScriptEnabled(true); 

          触摸焦点起作用

          requestFocus();

          取消滚动条

         this.setScrollBarStyle(SCROLLBARS_OUTSIDE_OVERLAY);

4如果希望点击链接由自己处理,而不是新开Android的系统browser中响应该链接。给WebView添加一个事件监听对象(WebViewClient)并重写其中的一些方法 shouldOverrideUrlLoading:对网页中超链接按钮的响应。 当按下某个连接时WebViewClient会调用这个方法,并传递参数:按下的url

             

[java]  view plain copy
  1. onLoadResource    
  2.   
  3. onPageStart   
  4.   
  5. onPageFinish   
  6.   
  7. onReceiveError  
  8.   
  9. onReceivedHttpAuthRequest  


5、如果访问的页面中有Javascript,则webview必须设置支持Javascript ,否则显示空白页面。

Java代码

      webview.getSettings().setJavaScriptEnabled(true);  
6、如果页面中链接,如果希望点击链接继续在当前browser中响应,而不是新开Android的系统browser中响应该链接,必须覆盖webview的WebViewClient对象:

Java代码

[java]  view plain copy
  1. mWebView.setWebViewClient(new WebViewClient(){     
  2.   
  3.     public boolean shouldOverrideUrlLoading(WebView view, String url) {    
  4.   
  5.         view.loadUrl(url);    
  6.   
  7.         return true;     
  8.   
  9.     }     
  10.   
  11. });    


上述方法告诉系统由我这个WebViewClient处理这个Intent,我来加载URL。点击一个链接的Intent是向上冒泡的,shouldOverrideUrlLoading方法return true表示我加载后这个Intent就消费了,不再向上冒泡了。

7、如果不做任何处理,在显示你的Brower UI时,点击系统“Back”键,整个Browser会作为一个整体“Back"到其他Activity中,而不是希望的在Browser的历史页面中 Back。如果希望实现在历史页面中Back,需要在当前Activity中处理并消费掉该Back事件:

Java代码

[java]  view plain copy
  1. public boolean onKeyDown(int keyCode, KeyEvent event) {    
  2.   
  3.     if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {    
  4.   
  5.         mWebView.goBack();    
  6.   
  7.         return true;     
  8.   
  9.     }     
  10.   
  11.     return super.onKeyDown(keyCode, event);    
  12.   
  13. }    


对于Android 2.0开始又多出了一种新的方法,对于Activity 可以单独获取Back键的按下事件,直接重写                 onBackPressed 方法即可,代码如下

Java代码

[java]  view plain copy
  1. @Override  
  2. public void onBackPressed() {  
  3.      // 这里处理逻辑代码,该方法仅适用于2.0或更高版本的sdk  
  4.     return ;  
  5. }  


 

这里还有几个知识点:

 

1)为了让WebView从apk文件中加载 assets,Android SDK提供了一个schema,前缀为"file:///android_asset/"。WebView遇到这样的schema,就去当前包中的 assets目录中找内容。如上面的"file:///android_asset/demo.html"

 

2)addJavascriptInterface方法中要绑定的 Java对象及方法要运行另外的线程中,不能运行在构造他的线程中,这也是使用Handler的目的。

 

Webview的两种显示网页的方法:

(1):webview.loadUrl(“www.baidu.com”);

[java]  view plain copy
  1. public class WebviewTest extendsActivity {  
  2.   
  3.     /** Called whenthe activity is first created. */  
  4.   
  5.     
  6.   
  7.           private WebView mWebView;  
  8.   
  9.             private Button bt1;  
  10.   
  11.             public void onCreate(Bundle savedInstanceState) {  
  12.   
  13.                 super.onCreate(savedInstanceState);  
  14.   
  15.                 setContentView(R.layout.main);  
  16.   
  17.                 mWebView =(WebView)findViewById(R.id.webview);  
  18.   
  19.                 WebSettings webSettings = mWebView.getSettings();  
  20.   
  21.                 webSettings.setJavaScriptEnabled(true);  
  22.   
  23.                  
  24.   
  25.                 bt1 = (Button)findViewById(R.id.Button01);  
  26.   
  27.                   
  28.   
  29.                 bt1.setOnClickListener(new View.OnClickListener() {  
  30.   
  31.                                       
  32.   
  33.                                       
  34.   
  35.                                      public voidonClick(View arg0) {  
  36.   
  37.                                                // TODO Auto-generated method stub  
  38.   
  39.                                                webview.loadUrl(“www.baidu.com”);  
  40.   
  41.                                      }  
  42.   
  43.                             });  
  44.   
  45.             }  
  46.   
  47.          }  


 

(2):自定义网页:Webview.data();

 

[java]  view plain copy
  1. public class WebviewTest extendsActivity {  
  2.   
  3.     /** Called whenthe activity is first created. */  
  4.   
  5.     
  6.   
  7.           private WebView mWebView;  
  8.   
  9.             private Button bt1;  
  10.   
  11.             public void onCreate(Bundle savedInstanceState) {  
  12.   
  13.                 super.onCreate(savedInstanceState);  
  14.   
  15.                 setContentView(R.layout.main);  
  16.   
  17.                 mWebView =(WebView)findViewById(R.id.webview);  
  18.   
  19.                  WebSettings webSettings = mWebView.getSettings();  
  20.   
  21.                 webSettings.setJavaScriptEnabled(true);  
  22.   
  23.                  
  24.   
  25.                 bt1 = (Button)findViewById(R.id.Button01);  
  26.   
  27.                   
  28.   
  29.                 bt1.setOnClickListener(new View.OnClickListener() {  
  30.   
  31.                                       
  32.   
  33.                                       
  34.   
  35.                                      public voidonClick(View arg0) {  
  36.   
  37.                                                // TODO Auto-generated method stub  
  38.   
  39.                                                Stringstr = "asdas";  
  40.   
  41.                                                  mWebView.loadData(  
  42.   
  43.                                                                 "<html><body>"+str+"</body></html>",  
  44.   
  45.                                                                 "text/html""utf-8");  
  46.   
  47.                                      }  
  48.   
  49.                             });  
  50.   
  51.             }  
  52.   
  53.          }  
  54.   
  55.    


Webview的常用方法实例:

 

Manifest.xml中的代码:

加入权限:

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

布局文件中的代码:

[html]  view plain copy
  1. <?xml version="1.0"encoding="utf-8"?>  
  2.   
  3. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  4.   
  5.          android:orientation="vertical"android:layout_width="fill_parent"  
  6.   
  7.          android:layout_height="fill_parent">  
  8.   
  9.          <WebView android:id="@+id/WebView01" android:layout_width="fill_parent"  
  10.   
  11.                    android:layout_height="fill_parent"></WebView>  
  12.   
  13. </LinearLayout>  


 

TestWebviewDemo中的代码:

[java]  view plain copy
  1. public class TestWebviewDemo extends Activity {  
  2.   
  3.          /** Calledwhen the activity is first created. */  
  4.   
  5.          privatestatic finalString TAG = "TestWebviewDemo";  
  6.   
  7.          privateWebView mWebView;  
  8.   
  9.          privateHandler mHandler = new Handler();  
  10.   
  11.          privateint mDensity;  
  12.   
  13.          publicvoid onCreate(BundlesavedInstanceState) {  
  14.   
  15.                    super.onCreate(savedInstanceState);  
  16.   
  17.                    setContentView(R.layout.main);  
  18.   
  19.    
  20.   
  21.                    mWebView= (WebView) findViewById(R.id.WebView01);  
  22.   
  23.                    mWebView.getSettings().setAllowFileAccess(true);// 设置允许访问文件数据  
  24.   
  25.                    mWebView.getSettings().setBuiltInZoomControls(true);// 设置支持缩放  
  26.   
  27.                    mWebView.getSettings().setSavePassword(false); // 设置是否保存密码  
  28.   
  29.                    //设置支持JavaScript脚本  
  30.   
  31. mWebView.getSettings().setJavaScriptEnabled(true);  
  32.   
  33. // 设置支持各种不同的设备  
  34.   
  35.                    mWebView  
  36.   
  37.                                      .getSettings()  
  38.   
  39.                                      .setUserAgentString(  
  40.   
  41.                                                         "Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X;en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334bSafari/531.21.10");  
  42.   
  43.         //通过这个设置来执行加载webview网页时所要执行的一些方法  
  44.   
  45.                    mWebView.setWebViewClient(new WebViewClient() {  
  46.   
  47.         // 新开页面时用自己定义的webview来显示,不用系统自带的浏览器来显示  
  48.   
  49.                             public booleanshouldOverrideUrlLoading(WebView view, String url) {  
  50.   
  51.                                      // TODO Auto-generated method stub  
  52.   
  53.                 // 当有新连接时使用当前的webview进行显示  
  54.   
  55.                                      view.loadUrl(url);  
  56.   
  57.                                      return super.shouldOverrideUrlLoading(view,url);  
  58.   
  59.                             }  
  60.   
  61.             // 开始加载网页时要做的工作  
  62.   
  63.                             public voidonPageStarted(WebView view, String url, Bitmap favicon) {  
  64.   
  65.    
  66.   
  67.                                      super.onPageStarted(view, url, favicon);  
  68.   
  69.                             }  
  70.   
  71. //加载完成时要做的工作  
  72.   
  73.                             public voidonPageFinished(WebView view, String url) {  
  74.   
  75.    
  76.   
  77.                                      super.onPageFinished(view, url);  
  78.   
  79.                             }  
  80.   
  81.             // 加载错误时要做的工作  
  82.   
  83.                             public voidonReceivedError(WebView view, interrorCode,  
  84.   
  85.                                                Stringdescription, String failingUrl) {  
  86.   
  87.                                      Log.d(TAG, "error="+ description);  
  88.   
  89.                                      Toast.makeText(TestWebviewDemo.this,  
  90.   
  91.                                                         errorCode+ "/" + description, Toast.LENGTH_LONG)  
  92.   
  93.                                                         .show();  
  94.   
  95.                             }  
  96.   
  97.                    });  
  98.   
  99.                    //处理网页中的一些对话框信息(提示对话框,带选择的对话框,带输入的对话框)  
  100.   
  101.                    mWebView.setWebChromeClient(new WebChromeClient() {  
  102.   
  103.             // 对话框  
  104.   
  105.                             public booleanonJsAlert(WebView view, String url, String message,  
  106.   
  107.                                                final JsResult result) {  
  108.   
  109.                                      // 构建一个Builder来显示网页中的alert对话框  
  110.   
  111.                                      Builderbuilder = newBuilder(TestWebviewDemo.this);  
  112.   
  113.                                      builder.setTitle("提示对话框");  
  114.   
  115.                                      builder.setMessage(message);  
  116.   
  117.                                      builder.setPositiveButton(android.R.string.ok,  
  118.   
  119.                                                         new AlertDialog.OnClickListener() {  
  120.   
  121.                                                                  @Override  
  122.   
  123.                                                                  public voidonClick(DialogInterface dialog,  
  124.   
  125.                                                                                     int which) {  
  126.   
  127.                                                                            // TODO Auto-generated method stub  
  128.   
  129.                                                                            result.confirm();  
  130.   
  131.                                                                  }  
  132.   
  133.                                                         });  
  134.   
  135.                                      builder.setCancelable(false);  
  136.   
  137.                                      builder.create();  
  138.   
  139.                                      builder.show();  
  140.   
  141.                                      return true;  
  142.   
  143.                             }  
  144.   
  145.             // 带按钮的对话框  
  146.   
  147.                             public booleanonJsConfirm(WebView view, String url,  
  148.   
  149.                                                Stringmessage, final JsResult result) {  
  150.   
  151.                                      Builderbuilder = newBuilder(TestWebviewDemo.this);  
  152.   
  153.                                      builder.setTitle("带选择的对话框");  
  154.   
  155.                                      builder.setMessage(message);  
  156.   
  157.                                      builder.setPositiveButton(android.R.string.ok,  
  158.   
  159.                                                         new AlertDialog.OnClickListener() {  
  160.   
  161.    
  162.   
  163.                                                                  @Override  
  164.   
  165.                                                                  public voidonClick(DialogInterface dialog,  
  166.   
  167.                                                                                     int which) {  
  168.   
  169.                                                                            // TODO Auto-generated method stub  
  170.   
  171.                                                                            result.confirm();  
  172.   
  173.                                                                  }  
  174.   
  175.    
  176.   
  177.                                                         });  
  178.   
  179.                                      builder.setNeutralButton(android.R.string.cancel,  
  180.   
  181.                                                         new AlertDialog.OnClickListener() {  
  182.   
  183.    
  184.   
  185.                                                                  @Override  
  186.   
  187.                                                                  public voidonClick(DialogInterface dialog,  
  188.   
  189.                                                                                     int which) {  
  190.   
  191.                                                                            // TODO Auto-generated method stub  
  192.   
  193.                                                                            result.cancel();  
  194.   
  195.                                                                  }  
  196.   
  197.    
  198.   
  199.                                                         });  
  200.   
  201.                                      builder.setCancelable(false);  
  202.   
  203.                                      builder.create();  
  204.   
  205.                                      builder.show();  
  206.   
  207.                                      return true;  
  208.   
  209.                             }  
  210.   
  211.             // 带输入框的对话框  
  212.   
  213.                             public booleanonJsPrompt(WebView view, String url, String message,  
  214.   
  215.                                                StringdefaultValue, final JsPromptResultresult) {  
  216.   
  217.                                      LayoutInflaterinflater = LayoutInflater  
  218.   
  219.                                                         .from(TestWebviewDemo.this);  
  220.   
  221.                                      final View v = inflater.inflate(R.layout.prom_dialog, null);  
  222.   
  223.                                      // 设置 TextView对应网页中的提示信息  
  224.   
  225.                                      ((TextView)v.findViewById(R.id.TextView_PROM))  
  226.   
  227.                                                         .setText(message);  
  228.   
  229.                                      // 设置EditText对应网页中的输入框  
  230.   
  231.                                      ((EditText)v.findViewById(R.id.EditText_PROM))  
  232.   
  233.                                                         .setText(defaultValue);  
  234.   
  235.                                      Builderbuilder = newBuilder(TestWebviewDemo.this);  
  236.   
  237.                                      builder.setTitle("带输入的对话框");  
  238.   
  239.                                      builder.setView(v);  
  240.   
  241.                                      builder.setPositiveButton(android.R.string.ok,  
  242.   
  243.                                                         new AlertDialog.OnClickListener() {  
  244.   
  245.    
  246.   
  247.                                                                  @Override  
  248.   
  249.                                                                  public voidonClick(DialogInterface dialog,  
  250.   
  251.                                                                                     int which) {  
  252.   
  253.                                                                            // TODO Auto-generated method stub  
  254.   
  255.                                                                           Stringvalue = ((EditText) v  
  256.   
  257.                                                                                              .findViewById(R.id.EditText_PROM))  
  258.   
  259.                                                                                              .getText().toString();  
  260.   
  261.                                                                            result.confirm(value);  
  262.   
  263.                                                                  }  
  264.   
  265.                                                         });  
  266.   
  267.                                      builder.setNegativeButton(android.R.string.cancel,  
  268.   
  269.                                                         new AlertDialog.OnClickListener() {  
  270.   
  271.    
  272.   
  273.                                                                  @Override  
  274.   
  275.                                                                  public voidonClick(DialogInterface dialog,  
  276.   
  277.                                                                                     int which) {  
  278.   
  279.                                                                            // TODO Auto-generated method stub  
  280.   
  281.                                                                            result.cancel();  
  282.   
  283.                                                                  }  
  284.   
  285.                                                         });  
  286.   
  287.                                      builder  
  288.   
  289.                                                         .setOnCancelListener(new DialogInterface.OnCancelListener() {  
  290.   
  291.    
  292.   
  293.                                                                  @Override  
  294.   
  295.                                                                  public voidonCancel(DialogInterface dialog) {  
  296.   
  297.                                                                            // TODO Auto-generated method stub  
  298.   
  299.                                                                            result.cancel();  
  300.   
  301.                                                                  }  
  302.   
  303.    
  304.   
  305.                                                         });  
  306.   
  307.                                      builder.create();  
  308.   
  309.                                      builder.show();  
  310.   
  311.                                      return true;  
  312.   
  313.    
  314.   
  315.                             }  
  316.   
  317.    
  318.   
  319.                             // 设置网页加载的进度条  
  320.   
  321.                             public voidonProgressChanged(WebView view, intnewProgress) {  
  322.   
  323.                                      TestWebviewDemo.this.getWindow().setFeatureInt(  
  324.   
  325.                                                         Window.FEATURE_PROGRESS, newProgress * 100);  
  326.   
  327.                                      super.onProgressChanged(view, newProgress);  
  328.   
  329.                             }  
  330.   
  331.    
  332.   
  333.                             // 设置应用程序的标题  
  334.   
  335.                             public voidonReceivedTitle(WebView view, String title) {  
  336.   
  337.                                      TestWebviewDemo.this.setTitle(title);  
  338.   
  339.                                      super.onReceivedTitle(view, title);  
  340.   
  341.                             }  
  342.   
  343.    
  344.   
  345.                    });  
  346.   
  347.        // 与网页进行交互的addJavascriptInterface()的方法  
  348.   
  349.                    mWebView.addJavascriptInterface(new Object() {  
  350.   
  351.                             public voidclickOnAndroid(final String str){  
  352.   
  353.                                      mHandler.post(newRunnable() {  
  354.   
  355.                                                @Override  
  356.   
  357.                                                public voidrun() {  
  358.   
  359.                                                // 逻辑代码  
  360.   
  361.                });  
  362.   
  363.                             }  
  364.   
  365.                    }, "demo");  
  366.   
  367.    
  368.   
  369.                    if(mDensity == 240) { //可以让不同的density的情况下,可以让页面进行适配  
  370.   
  371.                             mWebView.getSettings().setDefaultZoom(ZoomDensity.FAR);  
  372.   
  373.                    } elseif (mDensity== 160) {  
  374.   
  375.                             mWebView.getSettings().setDefaultZoom(ZoomDensity.MEDIUM);  
  376.   
  377.                    } else{  
  378.   
  379.                             mWebView.getSettings().setDefaultZoom(ZoomDensity.CLOSE);  
  380.   
  381.                    }  
  382.   
  383.                    String strUrl = "http://10.0.2.2:8080/WebTest3";  
  384.   
  385.                    mWebView.loadUrl(strUrl);  
  386.   
  387.          }  
  388.   
  389.     //处理返回的事件,(后退进入前一个界面而不是全部退出)  
  390.   
  391.          @Override  
  392.   
  393.          publicboolean onKeyDown(int keyCode, KeyEvent event) {  
  394.   
  395.                    if(keyCode == KeyEvent.KEYCODE_BACK&& mWebView.canGoBack()) {  
  396.   
  397.                             mWebView.goBack();// 返回前一个页面  
  398.   
  399.                             return true;  
  400.   
  401.                    }  
  402.   
  403.                    returnsuper.onKeyDown(keyCode, event);  
  404.   
  405.          }  
  406.   
  407.    
  408.   
  409.    


 

 

Webview中java与网页进行数据交互:

先看我们的html文档:

[html]  view plain copy
  1. <html>   
  2.   
  3.    <script language="javascript">   
  4.   
  5.        /* This function is invoked by the activity */    
  6.   
  7.        function wave() {    
  8.   
  9.            alert("1");    
  10.   
  11.            document.getElementById("droid").src="android_waving.png";    
  12.   
  13.            alert("2");    
  14.   
  15.        }    
  16.   
  17.    </script>   
  18.   
  19.    <body>   
  20.   
  21.        <!-- Calls into the javascript interface for the activity -->   
  22.   
  23.       //js调用Java方法  
  24.   
  25.        <a onClick="window.demo.clickOnAndroid()"><divstyledivstyle="width:80px;    
  26.   
  27.            margin:0px auto;    
  28.   
  29.            padding:10px;    
  30.   
  31.            text-align:center;    
  32.   
  33.            border:2px solid #202020;" >   
  34.   
  35.                 <img id="droid"src="android_normal.png"/><br>   
  36.   
  37.                 Click me!    
  38.   
  39.        </div></a>   
  40.   
  41.    </body>   
  42.   
  43. </html>    


 

Manifest.Xml中:

加入权限:

[html]  view plain copy
  1. <uses-permission android:name="android.permission.INTERNET" />     


 

再看我们的java 代码。

Java代码

[html]  view plain copy
  1. public class WebViewDemo extends Activity{    
  2.   
  3.    
  4.   
  5.    private static final String LOG_TAG = "WebViewDemo";    
  6.   
  7.    
  8.   
  9.    private WebView mWebView;    
  10.   
  11.    
  12.   
  13.    private Handler mHandler = new Handler();    
  14.   
  15.    
  16.   
  17.    @Override   
  18.   
  19.    public void onCreate(Bundle icicle) {    
  20.   
  21.        super.onCreate(icicle);    
  22.   
  23.        setContentView(R.layout.main);    
  24.   
  25.        mWebView = (WebView) findViewById(R.id.webview);    
  26.   
  27.    
  28.   
  29.        WebSettings webSettings = mWebView.getSettings();    
  30.   
  31.        webSettings.setSavePassword(false);    
  32.   
  33.        webSettings.setSaveFormData(false);    
  34.   
  35.        webSettings.setJavaScriptEnabled(true);    
  36.   
  37.        webSettings.setSupportZoom(false);    
  38.   
  39.    
  40.   
  41.        mWebView.setWebChromeClient(new MyWebChromeClient());    
  42.   
  43.         //自定义的Demo,供js网页调用  
  44.   
  45.        mWebView.addJavascriptInterface(new DemoJavaScriptInterface(),"demo");    
  46.   
  47.    
  48.   
  49.        mWebView.loadUrl("file:///android_asset/demo.html");    
  50.   
  51.   }  
  52.   
  53. final class DemoJavaScriptInterface {    
  54.   
  55.    
  56.   
  57.        DemoJavaScriptInterface() {    
  58.   
  59.        }    
  60.   
  61.    
  62.   
  63.         /**   
  64.   
  65.         * This is not called on the UI thread. Post a runnable to invoke   
  66.   
  67.         * loadUrl on the UI thread.   
  68.   
  69.         */   
  70.   
  71.        public void clickOnAndroid() {    
  72.   
  73.           //用handler来更新UI  
  74.   
  75.            mHandler.post(new Runnable() {    
  76.   
  77.                 public void run() {    
  78.   
  79.                     //Java调用js方法  
  80.   
  81.                    mWebView.loadUrl("javascript:wave()");    
  82.   
  83.                 }    
  84.   
  85.            });    
  86.   
  87.        }    
  88.   
  89.    }    
  90.   
  91.    /**   
  92.   
  93.     * Provides a hook for calling "alert" from javascript. Usefulfor   
  94.   
  95.     * debugging your javascript.   
  96.   
  97.     */   
  98.   
  99.    final class MyWebChromeClient extends WebChromeClient {    
  100.   
  101.        @Override   
  102.   
  103.        public boolean onJsAlert(WebView view, String url, String message,JsResult result) {    
  104.   
  105.            Log.d(LOG_TAG, message);    
  106.   
  107.            result.confirm();    
  108.   
  109.            return true;    
  110.   
  111.        }    
  112.   
  113.             
  114.   
  115.    }    
  116.   
  117. }   
  118.   
  119.    


 

再看个例子:

Html中的代码:

[html]  view plain copy
  1. <script type="text/JavaScript">       
  2.   
  3. functions(){    
  4.   
  5. alert("Good Morning!");        
  6.   
  7. }    
  8.   
  9. functiond(){    
  10.   
  11. confirm("Are you ok?")    
  12.   
  13. }    
  14.   
  15. functionf(){    
  16.   
  17. prompt("What’s yourname?")    
  18.   
  19. }    
  20.   
  21. </script>   
  22.   
  23.   </head>  
  24.   
  25.    
  26.   
  27.   <body>  
  28.   
  29.    <body>    
  30.   
  31.   下面我们演示三种对话框    
  32.   
  33.   <br/><br/>    
  34.   
  35.   <inputtypeinputtype="button" value="警告,提醒对话框" onclick="s()">    
  36.   
  37.   <br/><br/>    
  38.   
  39.   <inputtypeinputtype="button" value="带选择的对话框" onclick="d()">    
  40.   
  41.   <br/><br/>    
  42.   
  43.   <inputtypeinputtype="button" value="要求用户输入的对话框" onclick="f()">    
  44.   
  45.   </body>     


 

Manifest.Xml中:

加入权限:

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

 

Java中的代码:

[html]  view plain copy
  1. public class Test extendsActivity {    
  2.   
  3.     /** Called whenthe activity is first created. */   
  4.   
  5.     privateEditText et = null;    
  6.   
  7.     privateButton btn = null;    
  8.   
  9.     privateWebView wv = null;    
  10.   
  11.     privateWebSettings ws = null;    
  12.   
  13.     @Override   
  14.   
  15.     publicvoid onCreate(BundlesavedInstanceState) {    
  16.   
  17.         super.onCreate(savedInstanceState);    
  18.   
  19.         setContentView(R.layout.main);    
  20.   
  21.         et =(EditText) this.findViewById(R.id.EditText01);    
  22.   
  23.         btn= (Button) this.findViewById(R.id.Button01);    
  24.   
  25.         wv =(WebView) this.findViewById(R.id.WebView);    
  26.   
  27.         ws =wv.getSettings();    
  28.   
  29.         ws.setAllowFileAccess(true);//设置允许访问文件数据  
  30.   
  31.         ws.setJavaScriptEnabled(true);//设置支持javascript脚本    
  32.   
  33.         ws.setBuiltInZoomControls(true);//设置支持缩放    
  34.   
  35.         wv.requestFocus();    
  36.   
  37.         wv.setWebViewClient(new WebViewClient(){    
  38.   
  39.             publicbooleanshouldOverrideUrlLoading(WebView view,String url){    
  40.   
  41.                 //当有新连接时,使用当前的 WebView    
  42.   
  43.                 view.loadUrl(url);    
  44.   
  45.                 returntrue;    
  46.   
  47.             }    
  48.   
  49.         });    
  50.   
  51.         wv.setWebChromeClient(new WebChromeClient(){    
  52.   
  53.             publicboolean onJsAlert(WebView view,Stringurl,String message,final JsResultresult){    
  54.   
  55.                 //构建一个Builder来显示网页中的alert对话框    
  56.   
  57.                 Builder builder = new Builder(Test.this);    
  58.   
  59.                 builder.setTitle("提示对话框");    
  60.   
  61.                builder.setMessage(message);    
  62.   
  63.                 builder.setPositiveButton(android.R.string.ok, newAlertDialog.OnClickListener(){    
  64.   
  65.    
  66.   
  67.             
  68.   
  69.                     @Override   
  70.   
  71.                     publicvoid onClick(DialogInterface dialog, int which) {    
  72.   
  73.                         // TODO Auto-generated method stub    
  74.   
  75.                         result.confirm();    
  76.   
  77.                     }    
  78.   
  79.                         
  80.   
  81.                 });    
  82.   
  83.                 builder.setCancelable(false);    
  84.   
  85.                 builder.create();    
  86.   
  87.                 builder.show();    
  88.   
  89.                 returntrue;    
  90.   
  91.             }    
  92.   
  93.             publicboolean onJsConfirm(WebViewview,String url,String message,finalJsResult result){    
  94.   
  95.                 Builder builder = new Builder(Test.this);    
  96.   
  97.                 builder.setTitle("带选择的对话框");    
  98.   
  99.                builder.setMessage(message);    
  100.   
  101.                builder.setPositiveButton(android.R.string.ok,newAlertDialog.OnClickListener(){    
  102.   
  103.    
  104.   
  105.                     @Override   
  106.   
  107.                     publicvoid onClick(DialogInterface dialog, int which) {    
  108.   
  109.                         // TODO Auto-generated method stub    
  110.   
  111.                         result.confirm();    
  112.   
  113.                     }    
  114.   
  115.                         
  116.   
  117.                 });    
  118.   
  119.                 builder.setNeutralButton(android.R.string.cancel, newAlertDialog.OnClickListener(){    
  120.   
  121.    
  122.   
  123.                     @Override   
  124.   
  125.                     publicvoid onClick(DialogInterface dialog, int which) {    
  126.   
  127.                         // TODO Auto-generated method stub    
  128.   
  129.                         result.cancel();    
  130.   
  131.                     }    
  132.   
  133.                         
  134.   
  135.                 });    
  136.   
  137.                 builder.setCancelable(false);    
  138.   
  139.                 builder.create();    
  140.   
  141.                 builder.show();    
  142.   
  143.                 returntrue;    
  144.   
  145.             }    
  146.   
  147.             publicboolean onJsPrompt(WebViewview,String url,String message,String defaultValue,finalJsPromptResult result){    
  148.   
  149.                 LayoutInflater inflater =LayoutInflater.from(Test.this);    
  150.   
  151.                 finalView v = inflater.inflate(R.layout.prom_dialog,null);    
  152.   
  153.                 //设置 TextView对应网页中的提示信息    
  154.   
  155.                 ((TextView)v.findViewById(R.id.TextView_PROM)).setText(message);    
  156.   
  157.                 //设置EditText对应网页中的输入框    
  158.   
  159.                 ((EditText)v.findViewById(R.id.EditText_PROM)).setText(defaultValue);    
  160.   
  161.                 Builder builder = new Builder(Test.this);    
  162.   
  163.                 builder.setTitle("带输入的对话框 ");    
  164.   
  165.                 builder.setView(v);    
  166.   
  167.                builder.setPositiveButton(android.R.string.ok,newAlertDialog.OnClickListener(){    
  168.   
  169.    
  170.   
  171.                     @Override   
  172.   
  173.                     publicvoid onClick(DialogInterface dialog, int which) {    
  174.   
  175.                         // TODO Auto-generated method stub    
  176.   
  177.                         String value =((EditText)v.findViewById(R.id.EditText_PROM)).getText().toString();    
  178.   
  179.                        result.confirm(value);    
  180.   
  181.                     }    
  182.   
  183.                         
  184.   
  185.                 });    
  186.   
  187.                builder.setNegativeButton(android.R.string.cancel,newAlertDialog.OnClickListener(){    
  188.   
  189.    
  190.   
  191.                     @Override   
  192.   
  193.                     publicvoid onClick(DialogInterface dialog, int which) {    
  194.   
  195.                         // TODO Auto-generated method stub    
  196.   
  197.                         result.cancel();    
  198.   
  199.                     }    
  200.   
  201.                         
  202.   
  203.                 });    
  204.   
  205.                 builder.setOnCancelListener(new DialogInterface.OnCancelListener(){    
  206.   
  207.    
  208.   
  209.                     @Override   
  210.   
  211.                     publicvoid onCancel(DialogInterface dialog){    
  212.   
  213.                         // TODO Auto-generated method stub    
  214.   
  215.                         result.cancel();    
  216.   
  217.                     }    
  218.   
  219.                         
  220.   
  221.                 });    
  222.   
  223.                 builder.create();    
  224.   
  225.                 builder.show();    
  226.   
  227.                 returntrue;    
  228.   
  229.             }    
  230.   
  231.             //设置网页加载的进度条    
  232.   
  233.             publicvoid onProgressChanged(WebView view,int newProgress){    
  234.   
  235.                 Test.this.getWindow().setFeatureInt(Window.FEATURE_PROGRESS, newProgress*100);    
  236.   
  237.                 super.onProgressChanged(view,newProgress);    
  238.   
  239.             }    
  240.   
  241.             //设置应用程序的标题    
  242.   
  243.             publicvoid onReceivedTitle(WebViewview,String title){    
  244.   
  245.                 Test.this.setTitle(title);    
  246.   
  247.                 super.onReceivedTitle(view,title);    
  248.   
  249.             }    
  250.   
  251.         });    
  252.   
  253.         btn.setOnClickListener(new Button.OnClickListener(){    
  254.   
  255.    
  256.   
  257.             @Override   
  258.   
  259.             publicvoid onClick(View v) {    
  260.   
  261.                 // TODOAuto-generated method stub    
  262.   
  263.                 String url =et.getText().toString();    
  264.   
  265. //                  Stringurl = "http://10.0.2.2:8080/WebTest3";  
  266.   
  267.                 //判断输入的内容是不是网址    
  268.   
  269.                 if(URLUtil.isNetworkUrl(url)){   
  270.   
  271.                          Log.d("++++++++++++","sadas");  
  272.   
  273.                     wv.loadUrl(url);   
  274.   
  275.                     Toast.makeText(Test.this, url, Toast.LENGTH_SHORT).show();  
  276.   
  277.                 }else{    
  278.   
  279.                     et.setHint("输入的网址不合法,请重新输入");    
  280.   
  281. //                  et.setText("输入的网址不合法,请重新输入");    
  282.   
  283.                 }    
  284.   
  285.             }    
  286.   
  287.                 
  288.   
  289.         });    
  290.   
  291.     }    
  292.   
  293.     @Override   
  294.   
  295.     publicboolean onKeyDown(int keyCode, KeyEvent event) {    
  296.   
  297.         if(keyCode==KeyEvent.KEYCODE_BACK && wv.canGoBack()){    
  298.   
  299.             wv.goBack();//返回前一个页面    
  300.   
  301.             returntrue;    
  302.   
  303.         }    
  304.   
  305.         returnsuper.onKeyDown(keyCode, event);    
  306.   
  307.     }    
  308.   
  309.         
  310.   
  311. }   
  312.   
  313.    
  314.   
  315.    
  316.   
  317.    


需要注意的地方,很多数据类型js中不认识,最好是在android那边封装好,提供必要的方法接口。比如传到js中的list,在js中是没办法去得到里面的元素的。

 

Manifest.Xml中:

加入权限:

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

 

html的带码

[html]  view plain copy
  1.  <script language="javascript">  
  2.   
  3.           window.onloadfunction(){  
  4.   
  5.                         vari=window.javatojs.getSize();  
  6.   
  7.                         for(varn=0;n<i;n++){  
  8.   
  9.                 var jsdata=window.javatojs.getObject(n);//拿到activity里面的属性javadata  
  10.   
  11.            var datalistdiv = document.getElementById("datalist"); //得到页面的div  
  12.   
  13.            pnode = document.createElement("p");//创建一个p标签,再建个textnode  
  14.   
  15.            tnode = document.createTextNode(jsdata);  
  16.   
  17.            pnode.appendChild(tnode);//p中加入数据  
  18.   
  19.            datalistdiv.appendChild(pnode);//div中键入新的p  
  20.   
  21.      }  
  22.   
  23. }  
  24.   
  25. </script>  
  26.   
  27. <body>  
  28.   
  29. <div id = "datalist">  
  30.   
  31.          
  32.   
  33. this is a demo  
  34.   
  35. </body>  


 

Java的代码:

[java]  view plain copy
  1. public class JavaToWebview extends Activity{  
  2.   
  3.      
  4.   
  5.    private WebView web;  
  6.   
  7.    public List list;  
  8.   
  9.   @Override  
  10.   
  11.    public void onCreate(Bundle savedInstanceState) {  
  12.   
  13.        super.onCreate(savedInstanceState);  
  14.   
  15.        initData();  
  16.   
  17.        setContentView(R.layout.webview);  
  18.   
  19.        web = (WebView)this.findViewById(R.id.webview);  
  20.   
  21.        web.getSettings().setJavaScriptEnabled(true);//开启javascript设置  
  22.   
  23.        web.addJavascriptInterface(this"javatojs");//把RIAExample的一个实例添加到js的全局对象window中, //这样就可以使用window.javatojs来调用它的方法  
  24.   
  25.        web.loadUrl("file:///android_asset/demo5.html");//加载网页  
  26.   
  27.       
  28.   
  29.     }  
  30.   
  31.    void initData(){  
  32.   
  33.                list=newArrayList<String>();  
  34.   
  35.          for(int i=0;i<5;i++){  
  36.   
  37.                list.add("我是从数据库中读取的哈哈");  
  38.   
  39.          }  
  40.   
  41.     }  
  42.   
  43.    /** 
  44.  
  45.     * 该方法将在js脚本中,通过window.javatojs.....()进行调用 
  46.  
  47.     * @return 
  48.  
  49.     */  
  50.   
  51.    public Object getObject(int index){  
  52.   
  53.                    return list.get(index);  
  54.   
  55.     }  
  56.   
  57.    public int getSize(){  
  58.   
  59.             return list.size();  
  60.   
  61.     }  
  62.   
  63. }  
  64.   
  65.    


再看一个查地图的例子:

Manifest.Xml中:

加入权限:

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

布局文件中的代码:

[html]  view plain copy
  1. <?xml version="1.0"encoding="utf-8"?>       
  2.   
  3. <LinearLayoutxmlns:androidLinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"      
  4.   
  5.    android:orientation="vertical"      
  6.   
  7.    android:layout_width="fill_parent"      
  8.   
  9.    android:layout_height="fill_parent"      
  10.   
  11.    >       
  12.   
  13.    <TextView         
  14.   
  15.        android:layout_width="fill_parent"        
  16.   
  17.        android:layout_height="wrap_content"        
  18.   
  19.        android:text="Welcome to Mr Wei's Blog."      
  20.   
  21.        />       
  22.   
  23.    <WebView       
  24.   
  25.        android:id="@+id/webview"      
  26.   
  27.        android:layout_width="fill_parent"        
  28.   
  29.        android:layout_height="wrap_content"        
  30.   
  31.    />       
  32.   
  33.    <Button       
  34.   
  35.        android:id="@+id/button"      
  36.   
  37.        android:layout_width="fill_parent"      
  38.   
  39.        android:layout_height="wrap_content"      
  40.   
  41.        android:text="Change the webview content"      
  42.   
  43.    />       
  44.   
  45. </LinearLayout>      


在assets目录下新建一个demo.html文件,代码如下:

[html]  view plain copy
  1. <html>       
  2.   
  3.     <scriptlanguagescriptlanguage="javascript"><!--       
  4.   
  5.         
  6.   
  7.        function fillContent(){       
  8.   
  9.            document.getElementById("content").innerHTML =        
  10.   
  11.                  "This Content is showedby Android invoke Javascript function.";        
  12.   
  13.        }       
  14.   
  15.            
  16.   
  17. // --></script>         
  18.   
  19.  <body>       
  20.   
  21.    <p><a onClick="window.demo.startMap()"href="">Start GoogleMap</a></p>       
  22.   
  23.    <p id="content"></p>       
  24.   
  25.    <p>A Demo ----Android and Javascript invoke eachother.</p>       
  26.   
  27.    <p>Author:Frankiewei</p>       
  28.   
  29.  </body>       
  30.   
  31. </html>       


 

activity代码:

[java]  view plain copy
  1. public class WebViewDemo extends Activity{       
  2.   
  3.    private WebView mWebView;       
  4.   
  5.    private Button mButton;       
  6.   
  7.    public void onCreate(Bundle savedInstanceState) {       
  8.   
  9.        super.onCreate(savedInstanceState);       
  10.   
  11.        setContentView(R.layout.main);       
  12.   
  13.        setupViews();       
  14.   
  15.    }       
  16.   
  17.    //初始化       
  18.   
  19.    private void setupViews() {       
  20.   
  21.        mWebView = (WebView) findViewById(R.id.webview);       
  22.   
  23.         WebSettings mWebSettings =mWebView.getSettings();       
  24.   
  25.        //加上这句话才能使用javascript方法       
  26.   
  27.        mWebSettings.setJavaScriptEnabled(true);       
  28.   
  29.        //增加接口方法,让html页面调用       
  30.   
  31.        mWebView.addJavascriptInterface(new Object() {       
  32.   
  33.            //这里我定义了一个打开地图应用的方法       
  34.   
  35.            public void startMap() {       
  36.   
  37.                 Intent mIntent = newIntent();       
  38.   
  39.                 ComponentName component = newComponentName(       
  40.   
  41.                        "com.google.android.apps.maps",       
  42.   
  43.                        "com.google.android.maps.MapsActivity");       
  44.   
  45.                mIntent.setComponent(component);       
  46.   
  47.                 startActivity(mIntent);       
  48.   
  49.            }       
  50.   
  51.        }, "demo");       
  52.   
  53.        //加载页面       
  54.   
  55.        mWebView.loadUrl("file:///android_asset/demo.html");       
  56.   
  57.        mButton = (Button) findViewById(R.id.button);       
  58.   
  59.        //给button添加事件响应,执行JavaScript的fillContent()方法       
  60.   
  61.        mButton.setOnClickListener(new Button.OnClickListener() {       
  62.   
  63.            public void onClick(View v) {       
  64.   
  65.                mWebView.loadUrl("javascript:fillContent()");       
  66.   
  67.            }       
  68.   
  69.        });       
  70.   
  71.    }       
  72.   
  73. }      


 

 

其他例子如下:(activity中获取js界面输入框的值)

Jsp中的代码:

[html]  view plain copy
  1. <body>  
  2.   
  3.                    <form action="" method="post">  
  4.   
  5.                    宝宝预产期:<br>  
  6.   
  7.                    <select id="shijian" name="date">  
  8.   
  9.                        <optionvalueoptionvalue="2006">2006</option>  
  10.   
  11.                        <optionvalueoptionvalue="2007">2007</option>  
  12.   
  13.                        <optionvalueoptionvalue="2008">2008</option>  
  14.   
  15.                        <optionvalueoptionvalue="2009">2009</option>  
  16.   
  17.                        <optionvalueoptionvalue="2010">2010</option>  
  18.   
  19.                    </select><br>  
  20.   
  21.                             常用邮箱号:  
  22.   
  23.                             <input id="email" type="text" name="emailID" />  
  24.   
  25.                             <br>  
  26.   
  27.                             宝宝昵称:  
  28.   
  29.                             <input id="name" type="text" name="username" />  
  30.   
  31.                             <br>  
  32.   
  33.                             宝宝性别:<br>  
  34.   
  35.                             <input id="men" type="radio" name="sex" value="men"/>男  
  36.   
  37.                        <inputidinputid="women" type="radio" name="sex" value="women"/>女  
  38.   
  39.                        <br>  
  40.   
  41.                        <inputtypeinputtype="submit" value="注册"  
  42.   
  43.                                      onclick="f()"/>  
  44.   
  45.                             <input type="button" value="取消" />  
  46.   
  47.                    </form>  
  48.   
  49.          </body>  
  50.   
  51.          <script type="text/JavaScript"language="javascript">  
  52.   
  53.              functionf(){  
  54.   
  55.                 var emaildocument.getElementById('email').value;  
  56.   
  57.                 var name =document.getElementById('name').value;  
  58.   
  59.                 var date =document.getElementById('shijian').value;  
  60.   
  61.                 if(document.getElementById('men').checked &&!document.getElementById('women').checked){  
  62.   
  63.                 var sexdocument.getElementById('men').value;  
  64.   
  65.                 }elseif(!document.getElementById('men').checked &&document.getElementById('women').checked){  
  66.   
  67.                 var sexdocument.getElementById('women').value;  
  68.   
  69.                 }  
  70.   
  71.                 window.demo.clickOnAndroid(date+"|"+email+"|"+name+"|"+sex);           
  72.   
  73.          }      
  74.   
  75.                    </script>  


Manifest.xml中的代码:

[html]  view plain copy
  1. <?xml version="1.0"encoding="utf-8"?>  
  2.   
  3. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  4.   
  5.          package="com.ruixin.login"android:versionCode="1" android:versionName="1.0">  
  6.   
  7.          <applicationandroid:iconapplicationandroid:icon="@drawable/icon" android:label="@string/app_name">  
  8.   
  9.                    <activity android:name=".TestWebviewDemo" android:label="@string/app_name">  
  10.   
  11.                             <intent-filter>  
  12.   
  13.                                      <actionandroid:nameactionandroid:name="android.intent.action.MAIN" />  
  14.   
  15.                                      <categoryandroid:namecategoryandroid:name="android.intent.category.LAUNCHER"/>  
  16.   
  17.                             </intent-filter>  
  18.   
  19.                             <intent-filter>  
  20.   
  21.                                      <dataandroid:mimeTypedataandroid:mimeType="vnd.android.cursor.dir/vnd.ruixin.login"/>  
  22.   
  23.                             </intent-filter>  
  24.   
  25.                             <intent-filter>  
  26.   
  27.                                      <dataandroid:mimeTypedataandroid:mimeType="vnd.android.cursor.item/vnd.ruixin.login"/>  
  28.   
  29.                             </intent-filter>  
  30.   
  31.                              
  32.   
  33.                    </activity>  
  34.   
  35.                    <provider android:name="MyProvider" android:authorities="com.ruixin.login" />  
  36.   
  37.          </application>  
  38.   
  39.          <uses-sdk android:minSdkVersion="8" />  
  40.   
  41.          <uses-permissionandroid:nameuses-permissionandroid:name="android.permission.INTERNET" />  
  42.   
  43.          <uses-permissionandroid:nameuses-permissionandroid:name="android.permission.READ_CONTACTS"></uses-permission>  
  44.   
  45. </manifest>  


 

 

布局文件中的代码:

[html]  view plain copy
  1. <?xml version="1.0"encoding="utf-8"?>  
  2.   
  3. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  4.   
  5.          android:orientation="vertical"android:layout_width="fill_parent"  
  6.   
  7.          android:layout_height="fill_parent">  
  8.   
  9.          <WebView android:id="@+id/WebView01" android:layout_width="fill_parent"  
  10.   
  11.                    android:layout_height="fill_parent"></WebView>  
  12.   
  13. </LinearLayout>  


 

TestWebviewDemo中的代码:

[java]  view plain copy
  1. public class TestWebviewDemo extends Activity {  
  2.   
  3.          /** Calledwhen the activity is first created. */  
  4.   
  5.          privatestatic finalString TAG = "TestWebviewDemo";  
  6.   
  7.          privateWebView mWebView;  
  8.   
  9.          privateHandler mHandler = new Handler();  
  10.   
  11.          privateint mDensity;  
  12.   
  13.          publicvoid onCreate(BundlesavedInstanceState) {  
  14.   
  15.                    super.onCreate(savedInstanceState);  
  16.   
  17.                    setContentView(R.layout.main);  
  18.   
  19.    
  20.   
  21.                    mWebView= (WebView) findViewById(R.id.WebView01);  
  22.   
  23.                    mWebView.getSettings().setAllowFileAccess(true);// 设置允许访问文件数据  
  24.   
  25.                    mWebView.getSettings().setBuiltInZoomControls(true);// 设置支持缩放  
  26.   
  27.                    mWebView.getSettings().setSavePassword(false); // 设置是否保存密码  
  28.   
  29.                    //设置支持JavaScript脚本  
  30.   
  31. mWebView.getSettings().setJavaScriptEnabled(true);  
  32.   
  33. // 设置支持各种不同的设备  
  34.   
  35.                    mWebView  
  36.   
  37.                                      .getSettings()  
  38.   
  39.                                      .setUserAgentString(  
  40.   
  41.                                                         "Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X;en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334bSafari/531.21.10");  
  42.   
  43.         //通过这个设置来执行加载webview网页时所要执行的一些方法  
  44.   
  45.                    mWebView.setWebViewClient(new WebViewClient() {  
  46.   
  47.         // 新开页面时用自己定义的webview来显示,不用系统自带的浏览器来显示  
  48.   
  49.                             public booleanshouldOverrideUrlLoading(WebView view, String url) {  
  50.   
  51.                                      // TODO Auto-generated method stub  
  52.   
  53.                 // 当有新连接时使用当前的webview进行显示  
  54.   
  55.                                      view.loadUrl(url);  
  56.   
  57.                                      return super.shouldOverrideUrlLoading(view,url);  
  58.   
  59.                             }  
  60.   
  61.             // 开始加载网页时要做的工作  
  62.   
  63.                             public voidonPageStarted(WebView view, String url, Bitmap favicon) {  
  64.   
  65.    
  66.   
  67.                                       super.onPageStarted(view,url, favicon);  
  68.   
  69.                             }  
  70.   
  71. //加载完成时要做的工作  
  72.   
  73.                             public voidonPageFinished(WebView view, String url) {  
  74.   
  75.    
  76.   
  77.                                      super.onPageFinished(view, url);  
  78.   
  79.                             }  
  80.   
  81.             // 加载错误时要做的工作  
  82.   
  83.                             public voidonReceivedError(WebView view, interrorCode,  
  84.   
  85.                                                Stringdescription, String failingUrl) {  
  86.   
  87.                                      Log.d(TAG, "error="+ description);  
  88.   
  89.                                      Toast.makeText(TestWebviewDemo.this,  
  90.   
  91.                                                         errorCode+ "/" + description, Toast.LENGTH_LONG)  
  92.   
  93.                                                         .show();  
  94.   
  95.                             }  
  96.   
  97.                    });  
  98.   
  99.                    //处理网页中的一些对话框信息(提示对话框,带选择的对话框,带输入的对话框)  
  100.   
  101.                    mWebView.setWebChromeClient(new WebChromeClient() {  
  102.   
  103.             // 对话框  
  104.   
  105.                             public booleanonJsAlert(WebView view, String url, String message,  
  106.   
  107.                                                final JsResult result) {  
  108.   
  109.                                      // 构建一个Builder来显示网页中的alert对话框  
  110.   
  111.                                      Builderbuilder = newBuilder(TestWebviewDemo.this);  
  112.   
  113.                                       builder.setTitle("提示对话框");  
  114.   
  115.                                      builder.setMessage(message);  
  116.   
  117.                                      builder.setPositiveButton(android.R.string.ok,  
  118.   
  119.                                                         new AlertDialog.OnClickListener() {  
  120.   
  121.    
  122.   
  123.                                                                  @Override  
  124.   
  125.                                                                  public voidonClick(DialogInterface dialog,  
  126.   
  127.                                                                                     int which) {  
  128.   
  129.                                                                            // TODO Auto-generated method stub  
  130.   
  131.                                                                            result.confirm();  
  132.   
  133.                                                                  }  
  134.   
  135.                                                         });  
  136.   
  137.                                      builder.setCancelable(false);  
  138.   
  139.                                      builder.create();  
  140.   
  141.                                      builder.show();  
  142.   
  143.                                      return true;  
  144.   
  145.                             }  
  146.   
  147.             // 带按钮的对话框  
  148.   
  149.                             public booleanonJsConfirm(WebView view, String url,  
  150.   
  151.                                                Stringmessage, final JsResult result) {  
  152.   
  153.                                      Builderbuilder = newBuilder(TestWebviewDemo.this);  
  154.   
  155.                                      builder.setTitle("带选择的对话框");  
  156.   
  157.                                      builder.setMessage(message);  
  158.   
  159.                                      builder.setPositiveButton(android.R.string.ok,  
  160.   
  161.                                                         new AlertDialog.OnClickListener() {  
  162.   
  163.    
  164.   
  165.                                                                  @Override  
  166.   
  167.                                                                  public voidonClick(DialogInterface dialog,  
  168.   
  169.                                                                                     int which) {  
  170.   
  171.                                                                            // TODO Auto-generated method stub  
  172.   
  173.                                                                            result.confirm();  
  174.   
  175.                                                                  }  
  176.   
  177.    
  178.   
  179.                                                         });  
  180.   
  181.                                      builder.setNeutralButton(android.R.string.cancel,  
  182.   
  183.                                                         new AlertDialog.OnClickListener() {  
  184.   
  185.    
  186.   
  187.                                                                  @Override  
  188.   
  189.                                                                  public voidonClick(DialogInterface dialog,  
  190.   
  191.                                                                                     int which) {  
  192.   
  193.                                                                            // TODO Auto-generated method stub  
  194.   
  195.                                                                            result.cancel();  
  196.   
  197.                                                                  }  
  198.   
  199.    
  200.   
  201.                                                         });  
  202.   
  203.                                      builder.setCancelable(false);  
  204.   
  205.                                      builder.create();  
  206.   
  207.                                      builder.show();  
  208.   
  209.                                      return true;  
  210.   
  211.                             }  
  212.   
  213.             // 带输入框的对话框  
  214.   
  215.                             public booleanonJsPrompt(WebView view, String url, String message,  
  216.   
  217.                                                StringdefaultValue, final JsPromptResultresult) {  
  218.   
  219.                                      LayoutInflaterinflater = LayoutInflater  
  220.   
  221.                                                         .from(TestWebviewDemo.this);  
  222.   
  223.                                      final View v = inflater.inflate(R.layout.prom_dialog, null);  
  224.   
  225.                                      // 设置 TextView对应网页中的提示信息  
  226.   
  227.                                      ((TextView)v.findViewById(R.id.TextView_PROM))  
  228.   
  229.                                                         .setText(message);  
  230.   
  231.                                      // 设置EditText对应网页中的输入框  
  232.   
  233.                                      ((EditText)v.findViewById(R.id.EditText_PROM))  
  234.   
  235.                                                         .setText(defaultValue);  
  236.   
  237.                                      Builderbuilder = newBuilder(TestWebviewDemo.this);  
  238.   
  239.                                      builder.setTitle("带输入的对话框");  
  240.   
  241.                                      builder.setView(v);  
  242.   
  243.                                      builder.setPositiveButton(android.R.string.ok,  
  244.   
  245.                                                         new AlertDialog.OnClickListener() {  
  246.   
  247.    
  248.   
  249.                                                                  @Override  
  250.   
  251.                                                                  public voidonClick(DialogInterface dialog,  
  252.   
  253.                                                                                     int which) {  
  254.   
  255.                                                                            // TODO Auto-generated method stub  
  256.   
  257.                                                                            Stringvalue = ((EditText) v  
  258.   
  259.                                                                                              .findViewById(R.id.EditText_PROM))  
  260.   
  261.                                                                                              .getText().toString();  
  262.   
  263.                                                                            result.confirm(value);  
  264.   
  265.                                                                  }  
  266.   
  267.                                                         });  
  268.   
  269.                                      builder.setNegativeButton(android.R.string.cancel,  
  270.   
  271.                                                         new AlertDialog.OnClickListener() {  
  272.   
  273.    
  274.   
  275.                                                                  @Override  
  276.   
  277.                                                                  public voidonClick(DialogInterface dialog,  
  278.   
  279.                                                                                     int which) {  
  280.   
  281.                                                                            // TODO Auto-generated method stub  
  282.   
  283.                                                                            result.cancel();  
  284.   
  285.                                                                  }  
  286.   
  287.                                                         });  
  288.   
  289.                                      builder  
  290.   
  291.                                                         .setOnCancelListener(new DialogInterface.OnCancelListener() {  
  292.   
  293.    
  294.   
  295.                                                                  @Override  
  296.   
  297.                                                                  public voidonCancel(DialogInterface dialog) {  
  298.   
  299.                                                                            // TODO Auto-generated method stub  
  300.   
  301.                                                                            result.cancel();  
  302.   
  303.                                                                  }  
  304.   
  305.    
  306.   
  307.                                                         });  
  308.   
  309.                                      builder.create();  
  310.   
  311.                                      builder.show();  
  312.   
  313.                                      return true;  
  314.   
  315.    
  316.   
  317.                             }  
  318.   
  319.    
  320.   
  321.                             // 设置网页加载的进度条  
  322.   
  323.                             public voidonProgressChanged(WebView view, intnewProgress) {  
  324.   
  325.                                      TestWebviewDemo.this.getWindow().setFeatureInt(  
  326.   
  327.                                                         Window.FEATURE_PROGRESS, newProgress * 100);  
  328.   
  329.                                      super.onProgressChanged(view, newProgress);  
  330.   
  331.                             }  
  332.   
  333.    
  334.   
  335.                             // 设置应用程序的标题  
  336.   
  337.                             public voidonReceivedTitle(WebView view, String title) {  
  338.   
  339.                                      TestWebviewDemo.this.setTitle(title);  
  340.   
  341.                                      super.onReceivedTitle(view, title);  
  342.   
  343.                             }  
  344.   
  345.    
  346.   
  347.                    });  
  348.   
  349.        // 与网页进行交互的addJavascriptInterface()的方法  
  350.   
  351.                    mWebView.addJavascriptInterface(new Object() {  
  352.   
  353.                             public voidclickOnAndroid(final String str){  
  354.   
  355.                                      mHandler.post(newRunnable() {  
  356.   
  357.                                                @Override  
  358.   
  359.                                                public voidrun() {  
  360.   
  361.                                                StringTokenizerstringTokenizer = newStringTokenizer(  
  362.   
  363.                                                                            str,"|");  
  364.   
  365.                                                         date = stringTokenizer.nextToken();  
  366.   
  367.                                                         email = stringTokenizer.nextToken();  
  368.   
  369.                                                         username = stringTokenizer.nextToken();  
  370.   
  371.                                                         sex = stringTokenizer.nextToken();  
  372.   
  373.                           //将数据出入数据库  
  374.   
  375. dBlite1.add(email,username,date,sex);  
  376.   
  377. // 用contentResolver访问存入到contentprovider中的数据  
  378.   
  379. contentResolver = TestWebviewDemo.this  
  380.   
  381.                                                                            .getContentResolver();  
  382.   
  383.                                                         Log.d("++++", RuiXin.CONTENT_URI.toString());  
  384.   
  385.    
  386.   
  387.                                                         Cursorcursor = contentResolver.query(  
  388.   
  389.                                                                            RuiXin.CONTENT_URI, newString[] {  
  390.   
  391.                                                                                              RuiXin.EMAIL, RuiXin.USERNAME,  
  392.   
  393.                                                                                              RuiXin.DATE,RuiXin.SEX}, nullnull,null);  
  394.   
  395.                                                         Log.d("@@@----", cursor.toString());  
  396.   
  397.                                                         // startManagingCursor(cursor);  
  398.   
  399.                                                         while (cursor.moveToNext()) {  
  400.   
  401.                                                                  Toast.makeText(  
  402.   
  403.                                                                                     TestWebviewDemo.this,  
  404.   
  405.                                                                                     cursor.getString(cursor.getColumnIndex(RuiXin.EMAIL))  
  406.   
  407.                                                                                                        +" "  
  408.   
  409.                                                                                                        +cursor.getString(cursor  
  410.   
  411.                                                                                                                          .getColumnIndex(RuiXin.USERNAME))  
  412.   
  413.                                                                                                        +" "  
  414.   
  415.                                                                                                        +cursor.getString(cursor  
  416.   
  417.                                                                                                                          .getColumnIndex(RuiXin.DATE))  
  418.   
  419.                                                                                                  + " "  
  420.   
  421.                                                                                                  + cursor.getString(cursor  
  422.   
  423.                                                                                                                     .getColumnIndex(RuiXin.SEX)),  
  424.   
  425.                                                                                     Toast.LENGTH_SHORT).show();  
  426.   
  427.                                                         }  
  428.   
  429.                                                         startManagingCursor(cursor);   //关闭游标  
  430.   
  431.           }  
  432.   
  433.                });  
  434.   
  435.                             }  
  436.   
  437.                    }, "demo");  
  438.   
  439.    
  440.   
  441.                    if(mDensity == 240) { //可以让不同的density的情况下,可以让页面进行适配  
  442.   
  443.                             mWebView.getSettings().setDefaultZoom(ZoomDensity.FAR);  
  444.   
  445.                    } elseif (mDensity== 160) {  
  446.   
  447.                             mWebView.getSettings().setDefaultZoom(ZoomDensity.MEDIUM);  
  448.   
  449.                    } else{  
  450.   
  451.                             mWebView.getSettings().setDefaultZoom(ZoomDensity.CLOSE);  
  452.   
  453.                    }  
  454.   
  455.                    String strUrl = "http://10.0.2.2:8080/WebTest3";  
  456.   
  457.                    mWebView.loadUrl(strUrl);  
  458.   
  459.          }  
  460.   
  461.     //处理返回的事件,(后退进入前一个界面而不是全部退出)  
  462.   
  463.          @Override  
  464.   
  465.          publicboolean onKeyDown(int keyCode, KeyEvent event) {  
  466.   
  467.                    if(keyCode == KeyEvent.KEYCODE_BACK&& mWebView.canGoBack()) {  
  468.   
  469.                             mWebView.goBack();// 返回前一个页面  
  470.   
  471.                             return true;