zoukankan      html  css  js  c++  java
  • Android中WebView的使用

    Android中WebView的使用

    一、什么是WebView

    Android 中的WebView(网络视图),可以这么去理解,就是一个内置的浏览器。它使用了WebKit渲染引擎加载显示网页。

    二、WebView的使用方式

    1.实例化一个WebView

    2.调用WebView的loadUrl()方法,设置WevView要显示的网页:

      互联网用:webView.loadUrl("http://www.baidu.com"); 
      本地文件用:webView.loadUrl("file:///android_asset/XX.html"); 此本地文件存放于assets 文件中

    3.需要在AndroidManifest.xml文件中添加权限,否则会出现Web page not available错误。

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

    下面是简单的示例代码:
    1. import android.app.Activity;    
    2. import android.os.Bundle;    
    3. import android.view.KeyEvent;    
    4. import android.webkit.WebView;    
    5.    
    6. public class MainActivity extends Activity {    
    7.     private WebView webview;    
    8.     @Override   
    9.     public void onCreate(Bundle savedInstanceState) {    
    10.         super.onCreate(savedInstanceState);    
    11.         //实例化WebView对象    
    12.         webview = new WebView(this);    
    13.         //加载需要显示的网页    
    14.         webview.loadUrl("http://www.baidu.com/");    
    15.         //将Web视图作为activity的视图    
    16.         setContentView(webview);    
    17.     }    
    18.       
    19. }   


    4、不同的使用方法

    上面的示例代码,我们讲解了直接webview视图直接作为activity的视图,在实际项目当中,我们经常是需要将webview作为一部分嵌入到activity的视图中的。如果想这么做,我们需要先在布局文件中声明WebView。
    下面是示例代码:
    1. import android.app.Activity;    
    2. import android.os.Bundle;    
    3. import android.view.KeyEvent;    
    4. import android.webkit.WebView;    
    5. import android.webkit.WebViewClient;    
    6.    
    7. public class MainActivity extends Activity {    
    8.     private WebView webview;    
    9.     @Override   
    10.     public void onCreate(Bundle savedInstanceState) {    
    11.         super.onCreate(savedInstanceState);    
    12.         setContentView(R.layout.main);    
    13.         webview = (WebView) findViewById(R.id.webview);    
    14.         //加载需要显示的网页    
    15.         webview.loadUrl("http://www.baidu.com/");    
    16.     }    
    17.      
    18. }   


    xml示例代码:

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


    5、webview的关闭

    当我们在使用有声音播放的webview,我们如果直接finish掉webview做依赖的activity,我们会发现webview的声音播放还未停止,这是因为activity虽然被finish掉了,但是webview实际并未被销毁掉。
    我们需要调用webview的destroy方法销毁webview。
    下面是示例代码:
    1. //webview的销毁  
    2. public void stop() {  
    3.         web_view.destroy();  
    4.         ((Activity) getContext()).finish();  
    5.     }  


    三、webview的参数设置

    webview的参数有很多,下面我们直接上一段示例代码进行说明
    1. //设置支持js代码  
    2.         web_view.getSettings().setJavaScriptEnabled(true);  
    3.         //设置支持插件  
    4.         web_view.getSettings().setPluginState(PluginState.ON);  
    5.         //设置允许访问文件数据  
    6.         web_view.getSettings().setAllowFileAccess(true);  
    7.         //设置是否支持插件  
    8.         web_view.getSettings().setPluginsEnabled(true);  
    9.         //支持缩放  
    10.         web_view.getSettings().setSupportZoom(true);  
    11.         //支持缓存  
    12.         web_view.getSettings().setAppCacheEnabled(true);  
    13.         //设置缓存模式  
    14.         web_view.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);  
    15.         //设置此属性,可任意比例缩放  
    16.         web_view.getSettings().setUseWideViewPort(true);  
    17.         web_view.getSettings().setLoadWithOverviewMode(true);  


    四、WebViewClient的使用

    WebViewClient主要帮助WebView处理各种通知、请求事件的。比如:
    onLoadResource
    onPageStart
    onPageFinish
    onReceiveError
    onReceivedHttpAuthRequest
    例如以下示例代码:
    1. webView.setWebViewClient(new WebViewClient(){  
    2.   
    3.   
    4.                         @Override  
    5.                         public void onLoadResource(WebView view, String url) {  
    6.                                 super.onLoadResource(view, url);  
    7.                                 Log.i(TAG, "onLoadResource: ");  
    8.                         }  
    9.   
    10.   
    11.                         @Override  
    12.                         public void onPageFinished(WebView view, String url) {  
    13.                                 super.onPageFinished(view, url);  
    14.                                 Log.i(TAG, "onPageFinished: ");  
    15.                         }  
    16.   
    17.   
    18.                         @Override  
    19.                         public void onPageStarted(WebView view, String url, Bitmap favicon) {  
    20.                                 super.onPageStarted(view, url, favicon);  
    21.                                 Log.i(TAG, "onPageStarted: ");  
    22.                         }  
    23.   
    24.   
    25.                         @Override  
    26.                         public void onReceivedHttpAuthRequest(WebView view,  
    27.                                         HttpAuthHandler handler, String host, String realm) {  
    28.                                 super.onReceivedHttpAuthRequest(view, handler, host, realm);  
    29.                                 Log.i(TAG, "onReceivedHttpAuthRequest: ");  
    30.                         }  
    31.   
    32.   
    33.                         @Override  
    34.                         public void onReceivedSslError(WebView view,  
    35.                                         SslErrorHandler handler, SslError error) {  
    36.                                 super.onReceivedSslError(view, handler, error);  
    37.                                 Log.i(TAG, "onReceivedSslError: ");  
    38.                         }  
    39.   
    40.   
    41.                         @Override  
    42.                        public boolean shouldOverrideUrlLoading(WebView view, String url) {  
    43.                                 Log.i(TAG, "shouldOverrideUrlLoading: ");  
    44.                                return super.shouldOverrideUrlLoading(view, url);  
    45.                        }  
    46.   
    47.   
    48.                         @Override  
    49.                         public void onReceivedError(WebView view, int errorCode,  
    50.                                         String description, String failingUrl) {  
    51.                                 super.onReceivedError(view, errorCode, description, failingUrl);  
    52.                                 Log.i(TAG, "onReceivedError: ");  
    53.                                 Log.i(TAG, "errorCode: "+errorCode);  
    54.                                 Log.i(TAG, "description: "+description);  
    55.                                 Log.i(TAG, "failingUrl: "+failingUrl);  
    56.                         }  
    57.   
    58.   
    59.                         @Override  
    60.                         @Deprecated  
    61.                         public void onTooManyRedirects(WebView view, Message cancelMsg,  
    62.                                         Message continueMsg) {  
    63.                                 super.onTooManyRedirects(view, cancelMsg, continueMsg);  
    64.                                 Log.i(TAG, "onTooManyRedirects");  
    65.                         }  
    66.                           
    67.                           
    68.                           
    69.                 });  


    五、WebChromeClient的使用

    WebChromeClient主要辅助WebView处理Javascript的对话框、网站图标、网站title、加载进度等比如
    onCloseWindow(关闭WebView)
    onCreateWindow()
    onJsAlert (WebView上alert无效,需要定制WebChromeClient处理弹出)
    onJsPrompt
    onJsConfirm
    onProgressChanged
    onReceivedIcon
    onReceivedTitle


    例如以下示例代码:
    1. webView.setWebChromeClient(new WebChromeClient(){  
    2.   
    3.   
    4.                        @Override  
    5.                        public void getVisitedHistory(ValueCallback<String[]> callback) {  
    6.                                super.getVisitedHistory(callback);  
    7.                                Log.i(TAG, "getVisitedHistory");  
    8.                        }  
    9.   
    10.   
    11.                        @Override  
    12.                        public void onCloseWindow(WebView window) {  
    13.                                super.onCloseWindow(window);  
    14.                                Log.i(TAG, "onCloseWindow");  
    15.                        }  
    16.   
    17.   
    18.                        @Override  
    19.                        public boolean onCreateWindow(WebView view, boolean isDialog,  
    20.                                        boolean isUserGesture, Message resultMsg) {  
    21.                                Log.i(TAG, "onCreateWindow");  
    22.                                return super.onCreateWindow(view, isDialog, isUserGesture, resultMsg);  
    23.                        }  
    24.   
    25.   
    26.                        @Override  
    27.                        @Deprecated  
    28.                        public void onExceededDatabaseQuota(String url,  
    29.                                        String databaseIdentifier, long quota,  
    30.                                        long estimatedDatabaseSize, long totalQuota,  
    31.                                        QuotaUpdater quotaUpdater) {  
    32.                                super.onExceededDatabaseQuota(url, databaseIdentifier, quota,  
    33.                                                estimatedDatabaseSize, totalQuota, quotaUpdater);  
    34.                                Log.i(TAG, "onExceededDatabaseQuota");  
    35.                        }  
    36.   
    37.   
    38.                        @Override  
    39.                        public void onProgressChanged(WebView view, int newProgress) {  
    40.                                super.onProgressChanged(view, newProgress);  
    41.                                Log.i(TAG, "onProgressChanged newProgress "+newProgress);  
    42.                        }  
    43.   
    44.   
    45.                        @Override  
    46.                        public void onReceivedIcon(WebView view, Bitmap icon) {  
    47.                                super.onReceivedIcon(view, icon);  
    48.                                Log.i(TAG, "gonReceivedIcon");  
    49.                        }  
    50.   
    51.   
    52.                        @Override  
    53.                        public void onReceivedTitle(WebView view, String title) {  
    54.                                super.onReceivedTitle(view, title);  
    55.                                Log.i(TAG, "onReceivedTitle");  
    56.                        }  
    57.   
    58.   
    59.                        @Override  
    60.                        public void onRequestFocus(WebView view) {  
    61.                                super.onRequestFocus(view);  
    62.                                Log.i(TAG, "onRequestFocus");  
    63.                        }  
    64.                });  


    六、一些使用的小技巧

    1、打开Android本地文件。

    当网页html文件中有使用到input type=“file”的时候,Android的webview默认是不支持这个标签的,那需要怎么做呢。
    这个时候需要重写webview的WebChromeClient,以下是示例代码:
    1. webView.setWebChromeClient(new WebChromeClient() {  
    2.             public void openFileChooser(ValueCallback<Uri> uploadMsg) {  
    3.   
    4.   
    5.                 mUploadMessage = uploadMsg;  
    6.                 Intent i = new Intent(Intent.ACTION_GET_CONTENT);  
    7.                 i.addCategory(Intent.CATEGORY_OPENABLE);  
    8.                 i.setType("image/*");  
    9.                 ChangeImgActivity.this.startActivityForResult(  
    10.                         Intent.createChooser(i, "File Chooser"),  
    11.                         FILECHOOSER_RESULTCODE);  
    12.   
    13.   
    14.             }  
    15.   
    16.   
    17.             public void openFileChooser(ValueCallback uploadMsg,  
    18.                     String acceptType) {  
    19.                 mUploadMessage = uploadMsg;  
    20.                 Intent i = new Intent(Intent.ACTION_GET_CONTENT);  
    21.                 i.addCategory(Intent.CATEGORY_OPENABLE);  
    22.                 i.setType("*/*");  
    23.                 ChangeImgActivity.this.startActivityForResult(  
    24.                         Intent.createChooser(i, "File Browser"),  
    25.                         FILECHOOSER_RESULTCODE);  
    26.             }  
    27.   
    28.   
    29.             public void openFileChooser(ValueCallback<Uri> uploadMsg,  
    30.                     String acceptType, String capture) {  
    31.                 mUploadMessage = uploadMsg;  
    32.                 Intent i = new Intent(Intent.ACTION_GET_CONTENT);  
    33.                 i.addCategory(Intent.CATEGORY_OPENABLE);  
    34.                 i.setType("image/*");  
    35.                 ChangeImgActivity.this.startActivityForResult(  
    36.                         Intent.createChooser(i, "File Chooser"),  
    37.                         ChangeImgActivity.FILECHOOSER_RESULTCODE);  
    38.   
    39.   
    40.             }  
    41.   
    42.   
    43.         });  

    2、浏览网页的回退。

    当我们在使用一些浏览器浏览网页的时候,经常会遇到这种功能,点击Android的返回键,就会产生网页回退,这个功能应该如何实现呢。
    以下是示例代码:
    1. webView.setOnKeyListener(new View.OnKeyListener() {  
    2.             @Override  
    3.             public boolean onKey(View v, int keyCode, KeyEvent event) {  
    4.                 if (event.getAction() == KeyEvent.ACTION_DOWN) {  
    5.                     if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {  
    6.                         webView.goBack();  
    7.                         return true;  
    8.                     }  
    9.                 }  
    10.                 return false;  
    11.             }  
    12.         });  


    3、Android中Java代码和网页中js代码的交互。

    在开发中,有时候需要使用Java代码去调用网页中的js代码,或者js代码要调用Java的代码。要实现此功能,首先要设置webview的参数。
    Java调用js代码较为简单,直接使用loadUrl方法即可。
    1. flash_view.loadUrl("javascript:Play()");  


    js代码回调Java代码较为复杂一点。Java 代码:
    //设置支持js代码
    1. web_view.getSettings().setJavaScriptEnabled(true);  
    2. //设置js代码的回调  
    3. web_view.addJavascriptInterface(new CallJava(), "CallJava");  
    4. //js代码的回调  
    5. private final class CallJava{  
    6.         public void consoleFlashProgress(float progressSize, int total){  
    7.             //设置播放进度条  
    8.             showFlashProgress(progressSize, total);  
    9.         }  
    10.     }  


    JS 代码:
    //动态显示播放影片的当前桢/总桢数(进度条显示)
    [javascript] view plaincopyprint?在CODE上查看代码片派生到我的代码片
     
    1. function showcount(){  
    2.                 total = movie.TotalFrames();  
    3.                 frame_number = movie.CurrentFrame();  
    4.                 frame_number++;  
    5.                 var progressSize = 500*(frame_number/total);  
    6.                 CallJava.consoleFlashProgress(progressSize,total/12);  
    7.             }  


    注:一下代码很大一部分摘抄自网络,在此感谢各位代码提供者。作者只是做了整理和总结,希望能帮到各位开发者
  • 相关阅读:
    Android Push Notification实现信息推送使用
    线段树 Interval Tree
    树状数组
    LCA和RMQ
    RMQ (Range Minimal Query) 问题 ,稀疏表 ST
    winner tree 胜者树
    ORA-64379: Action cannot be performed on the tablespace assigned to FastStart while the feature is enabled
    mybatis 查询优化主子表查询之association和collection
    Oracle 11gR2 用户重命名(rename user)
    redis.clients.jedis.exceptions.JedisConnectionException: java.net.SocketException: 断开的管道 (Write failed)
  • 原文地址:https://www.cnblogs.com/earl-yongchang/p/4929445.html
Copyright © 2011-2022 走看看