【FastDev4Android框架开发】重写WebView网页加载以及JavaScript注入详解(二十三)

来源:互联网 发布:暴走大事件禁播了知乎 编辑:程序博客网 时间:2024/06/05 17:42

转载请标明出处: 

http://blog.csdn.net/developer_jiangqq/article/details/49687613
本文出自:【江清清的博客】

().前言:   

         【好消息】个人网站已经上线运行,后面博客以及技术干货等精彩文章会同步更新,请大家关注收藏:http://www.lcode.org

       今天我们来学习一下重写WebView组件来实现网页的加载,以及我们平时APP开发中经常使用的JS注入,js和Java相互调用的问题来重点讲解一下。如果大家都WebView加载还不是太熟悉的话,这边我之前专门写了一个WebView的专题,其他包含基本使用和js注入的问题。(点击进入WebView进阶专题)

        FastDev4Android框架项目地址:https://github.com/jiangqqlmj/FastDev4Android

().重写WebView:   

        2.1首先我们来看一下实现的效果:


 


 2.2.重写WebView:创建一个HTML5CustomWebView类集成自WebView,然后就是一下几个步骤实现:

  •  布局文件
  •  WebSettings初始化相关设置
  •  设置重写WebChromeClient进行相关处理
  • 设置重写WebViewClient进行相关处理即可

   简单的来说就是以上这几步就可以了

2.3.WebView布局文件主要定义导航栏,网页加载进度,以及WebView容器布局,如下:

[html] view plain copy
print?
  1. <?xmlversionxmlversion=“1.0” encoding=“utf-8”?>  
  2. <FrameLayoutxmlns:androidFrameLayoutxmlns:android=“http://schemas.android.com/apk/res/android”  
  3.    android:layout_width=“fill_parent”  
  4.    android:layout_height=“fill_parent”  
  5.    android:background=“@color/white”>  
  6.     <RelativeLayout  
  7.        android:layout_width=“fill_parent”  
  8.        android:layout_height=“fill_parent”>  
  9.         <FrameLayout  
  10.            android:id=“@+id/fullscreen_custom_content”  
  11.            android:layout_width=“fill_parent”  
  12.            android:layout_height=“fill_parent”  
  13.            android:background=“@color/white”  
  14.             android:visibility=“gone”/>  
  15.         <LinearLayout  
  16.            android:layout_width=“fill_parent”  
  17.            android:layout_height=“fill_parent”  
  18.            android:orientation=“vertical” >  
  19.             <!– 自定义顶部导航功能条 –>  
  20.             <includelayoutincludelayout=“@layout/common_top_bar_layout” />  
  21.             <!– 中间显示内容 –>  
  22.             <FrameLayout  
  23.                android:id=“@+id/main_content”  
  24.                android:layout_width=“fill_parent”  
  25.                android:layout_height=“fill_parent”  
  26.                android:visibility=“gone” />  
  27.             <!– 网页加载进度显示 –>  
  28.             <FrameLayout  
  29.                android:id=“@+id/frame_progress”  
  30.                android:layout_width=“fill_parent”  
  31.                android:layout_height=“fill_parent”  
  32.                android:visibility=“visible” >  
  33.                 <LinearLayout  
  34.                    android:layout_width=“wrap_content”  
  35.                    android:layout_height=“wrap_content”  
  36.                    android:layout_gravity=“center”  
  37.                    android:orientation=“vertical” >  
  38.    
  39.                     <ProgressBar  
  40.                        style=“@android:style/Widget.ProgressBar.Small”  
  41.                        android:layout_width=“wrap_content”  
  42.                        android:layout_height=“wrap_content”  
  43.                        android:layout_gravity=“center_horizontal”  
  44.                        android:indeterminate=“false”  
  45.                        android:indeterminateDrawable=“@drawable/loading_small” />  
  46.    
  47.                     <TextView  
  48.                        android:id=“@+id/webview_tv_progress”  
  49.                        android:layout_width=“wrap_content”  
  50.                        android:layout_height=“wrap_content”  
  51.                        android:layout_marginTop=“3dip”  
  52.                        android:text=“正在加载,已完成0%…”  
  53.                        android:textSize=“12sp” />  
  54.                 </LinearLayout>  
  55.             </FrameLayout>  
  56.         </LinearLayout>  
  57.     </RelativeLayout>  
  58.    
  59. </FrameLayout>  
<?xmlversion="1.0" encoding="utf-8"?><FrameLayoutxmlns:android="http://schemas.android.com/apk/res/android"   android:layout_width="fill_parent"   android:layout_height="fill_parent"   android:background="@color/white">    <RelativeLayout       android:layout_width="fill_parent"       android:layout_height="fill_parent">        <FrameLayout           android:id="@+id/fullscreen_custom_content"           android:layout_width="fill_parent"           android:layout_height="fill_parent"           android:background="@color/white"            android:visibility="gone"/>        <LinearLayout           android:layout_width="fill_parent"           android:layout_height="fill_parent"           android:orientation="vertical" >            <!-- 自定义顶部导航功能条 -->            <includelayout="@layout/common_top_bar_layout" />            <!-- 中间显示内容 -->            <FrameLayout               android:id="@+id/main_content"               android:layout_width="fill_parent"               android:layout_height="fill_parent"               android:visibility="gone" />            <!-- 网页加载进度显示 -->            <FrameLayout               android:id="@+id/frame_progress"               android:layout_width="fill_parent"               android:layout_height="fill_parent"               android:visibility="visible" >                <LinearLayout                   android:layout_width="wrap_content"                   android:layout_height="wrap_content"                   android:layout_gravity="center"                   android:orientation="vertical" >                    <ProgressBar                       style="@android:style/Widget.ProgressBar.Small"                       android:layout_width="wrap_content"                       android:layout_height="wrap_content"                       android:layout_gravity="center_horizontal"                       android:indeterminate="false"                       android:indeterminateDrawable="@drawable/loading_small" />                    <TextView                       android:id="@+id/webview_tv_progress"                       android:layout_width="wrap_content"                       android:layout_height="wrap_content"                       android:layout_marginTop="3dip"                       android:text="正在加载,已完成0%..."                       android:textSize="12sp" />                </LinearLayout>            </FrameLayout>        </LinearLayout>    </RelativeLayout></FrameLayout>

   2.4.WebSettings初始化设置如下:

[java] view plain copy
print?
  1. WebSettingswebSettings = this.getSettings();  
  2. webSettings.setJavaScriptEnabled(true);  //开启javascript  
  3. webSettings.setDomStorageEnabled(true);  //开启DOM  
  4. webSettings.setDefaultTextEncodingName(”utf-8”);//设置编码  
  5. // // web页面处理  
  6. webSettings.setAllowFileAccess(true);// 支持文件流  
  7. // webSettings.setSupportZoom(true);// 支持缩放  
  8. // webSettings.setBuiltInZoomControls(true);// 支持缩放  
  9. webSettings.setUseWideViewPort(true);// 调整到适合webview大小  
  10. webSettings.setLoadWithOverviewMode(true);//调整到适合webview大小  
  11. webSettings.setDefaultZoom(ZoomDensity.FAR);//屏幕自适应网页,如果没有这个,在低分辨率的手机上显示可能会异常  
  12. webSettings.setRenderPriority(RenderPriority.HIGH);  
  13. //提高网页加载速度,暂时阻塞图片加载,然后网页加载好了,在进行加载图片  
  14. webSettings.setBlockNetworkImage(true);  
  15. //开启缓存机制  
  16. webSettings.setAppCacheEnabled(true);  
  17. //根据当前网页连接状态  
  18.  if(StrUtils.getAPNType(context)==StrUtils.WIFI){  
  19.  //设置无缓存  
  20.  webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);  
  21.  }else{  
  22.  //设置缓存  
  23.  webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);  
  24.  }  
WebSettingswebSettings = this.getSettings();webSettings.setJavaScriptEnabled(true);  //开启javascriptwebSettings.setDomStorageEnabled(true);  //开启DOMwebSettings.setDefaultTextEncodingName("utf-8");//设置编码// // web页面处理webSettings.setAllowFileAccess(true);// 支持文件流// webSettings.setSupportZoom(true);// 支持缩放// webSettings.setBuiltInZoomControls(true);// 支持缩放webSettings.setUseWideViewPort(true);// 调整到适合webview大小webSettings.setLoadWithOverviewMode(true);//调整到适合webview大小webSettings.setDefaultZoom(ZoomDensity.FAR);//屏幕自适应网页,如果没有这个,在低分辨率的手机上显示可能会异常webSettings.setRenderPriority(RenderPriority.HIGH);//提高网页加载速度,暂时阻塞图片加载,然后网页加载好了,在进行加载图片webSettings.setBlockNetworkImage(true);//开启缓存机制webSettings.setAppCacheEnabled(true);//根据当前网页连接状态 if(StrUtils.getAPNType(context)==StrUtils.WIFI){ //设置无缓存 webSettings.setCacheMode(WebSettings.LOAD_DEFAULT); }else{ //设置缓存 webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); }
              

     2.5.WebChromeClient进行相关设置处理

[java] view plain copy
print?
  1. private classMyWebChromeClient extends WebChromeClient {  
  2. privateBitmap mDefaultVideoPoster;  
  3. @Override  
  4. publicvoid onShowCustomView(View view,  
  5. CustomViewCallbackcallback) {  
  6. super.onShowCustomView(view,callback);  
  7. HTML5CustomWebView.this.setVisibility(View.GONE);  
  8. if(mCustomView != null) {  
  9. callback.onCustomViewHidden();  
  10. return;  
  11. }  
  12. mCustomViewContainer.addView(view);  
  13. mCustomView= view;  
  14. mCustomViewCallback= callback;  
  15. mCustomViewContainer.setVisibility(View.VISIBLE);  
  16. }  
  17.    
  18. @Override  
  19. publicvoid onHideCustomView() {  
  20. if(mCustomView == null) {  
  21. return;  
  22. }  
  23. mCustomView.setVisibility(View.GONE);  
  24. mCustomViewContainer.removeView(mCustomView);  
  25. mCustomView= null;  
  26. mCustomViewContainer.setVisibility(View.GONE);  
  27. mCustomViewCallback.onCustomViewHidden();  
  28. HTML5CustomWebView.this.setVisibility(View.VISIBLE);  
  29. super.onHideCustomView();  
  30. }  
  31.    
  32. /** 
  33.  * 网页加载标题回调 
  34.  * @param view 
  35.  * @param title 
  36.  */  
  37. @Override  
  38. publicvoid onReceivedTitle(WebView view, String title) {  
  39. Log.d(”zttjiangqq”“当前网页标题为:” + title);  
  40. wv_tv_title.setText(title);  
  41. }  
  42.    
  43. /** 
  44.  * 网页加载进度回调 
  45.  * @param view 
  46.  * @param newProgress 
  47.  */  
  48. @Override  
  49. publicvoid onProgressChanged(WebView view, int newProgress) {  
  50. // 设置进行进度  
  51. ((Activity)mContext).getWindow().setFeatureInt(  
  52. Window.FEATURE_PROGRESS,newProgress * 100);  
  53. webview_tv_progress.setText(”正在加载,已完成” +newProgress + “%…”);  
  54. webview_tv_progress.postInvalidate(); //刷新UI  
  55. Log.d(”zttjiangqq”“进度为:” + newProgress);  
  56. }  
  57.    
  58. @Override  
  59. publicboolean onJsAlert(WebView view, String url, String message,  
  60. JsResultresult) {  
  61. returnsuper.onJsAlert(view, url, message, result);  
  62.    
  63. }  
  64. }  
private classMyWebChromeClient extends WebChromeClient {privateBitmap mDefaultVideoPoster;@Overridepublicvoid onShowCustomView(View view,CustomViewCallbackcallback) {super.onShowCustomView(view,callback);HTML5CustomWebView.this.setVisibility(View.GONE);if(mCustomView != null) {callback.onCustomViewHidden();return;}mCustomViewContainer.addView(view);mCustomView= view;mCustomViewCallback= callback;mCustomViewContainer.setVisibility(View.VISIBLE);}@Overridepublicvoid onHideCustomView() {if(mCustomView == null) {return;}mCustomView.setVisibility(View.GONE);mCustomViewContainer.removeView(mCustomView);mCustomView= null;mCustomViewContainer.setVisibility(View.GONE);mCustomViewCallback.onCustomViewHidden();HTML5CustomWebView.this.setVisibility(View.VISIBLE);super.onHideCustomView();}/** * 网页加载标题回调 * @param view * @param title */@Overridepublicvoid onReceivedTitle(WebView view, String title) {Log.d("zttjiangqq", "当前网页标题为:" + title);wv_tv_title.setText(title);}/** * 网页加载进度回调 * @param view * @param newProgress */@Overridepublicvoid onProgressChanged(WebView view, int newProgress) {// 设置进行进度((Activity)mContext).getWindow().setFeatureInt(Window.FEATURE_PROGRESS,newProgress * 100);webview_tv_progress.setText("正在加载,已完成" +newProgress + "%...");webview_tv_progress.postInvalidate(); //刷新UILog.d("zttjiangqq", "进度为:" + newProgress);}@Overridepublicboolean onJsAlert(WebView view, String url, String message,JsResultresult) {returnsuper.onJsAlert(view, url, message, result);}}

  2.6.WebViewClient进行相关设置处理

[java] view plain copy
print?
  1. private classMyWebViewClient extends WebViewClient {  
  2. /** 
  3.  *加载过程中 拦截加载的地址url 
  4.  * @param view 
  5.  *@param url  被拦截的url 
  6.  * @return 
  7.  */  
  8. @Override  
  9. publicboolean shouldOverrideUrlLoading(WebView view, String url) {  
  10. Log.i(”zttjiangqq”,“——–>shouldOverrideUrlLoading url:” + url);  
  11. //这边因为考虑到之前项目的问题,这边拦截的url过滤掉了zttmall://开头的地址  
  12. //在其他项目中 大家可以根据实际情况选择不拦截任何地址,或者有选择性拦截  
  13. if(!url.startsWith(“zttmall://”)){  
  14. UrimUri = Uri.parse(url);  
  15. List<String>browerList = new ArrayList<String>();  
  16. browerList.add(”http”);  
  17. browerList.add(”https”);  
  18. browerList.add(”about”);  
  19. browerList.add(”javascript”);  
  20. if(browerList.contains(mUri.getScheme())) {  
  21. returnfalse;  
  22. }else {  
  23. Intentintent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));  
  24. intent.addCategory(Intent.CATEGORY_BROWSABLE);  
  25. //如果另外的应用程序WebView,我们可以进行重用  
  26. intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
  27. intent.putExtra(Browser.EXTRA_APPLICATION_ID,  
  28. FDApplication.getInstance()  
  29. .getApplicationContext().getPackageName());  
  30. try{  
  31. FDApplication.getInstance().startActivity(intent);  
  32. returntrue;  
  33. }catch (ActivityNotFoundException ex) {  
  34. }  
  35. }  
  36. returnfalse;  
  37. }else{  
  38. returntrue;  
  39. }  
  40. }  
  41. /** 
  42.  * 页面加载过程中,加载资源回调的方法 
  43.  * @param view 
  44.  * @param url 
  45.  */  
  46. @Override  
  47. publicvoid onLoadResource(WebView view, String url) {  
  48. super.onLoadResource(view,url);  
  49. Log.i(”zttjiangqq”,“——–>onLoadResource url:” + url);  
  50. }  
  51. /** 
  52.  * 页面加载完成回调的方法 
  53.  * @param view 
  54.  * @param url 
  55.  */  
  56. @Override  
  57. publicvoid onPageFinished(WebView view, String url) {  
  58. super.onPageFinished(view,url);  
  59. Log.i(”zttjiangqq”,“——–>onPageFinished url:” + url);  
  60. if(isRefresh) {  
  61. isRefresh= false;  
  62. }  
  63. // 加载完成隐藏进度界面,显示WebView内容  
  64. frame_progress.setVisibility(View.GONE);  
  65. mContentView.setVisibility(View.VISIBLE);  
  66. // 关闭图片加载阻塞  
  67. view.getSettings().setBlockNetworkImage(false);  
  68.    
  69. }  
  70. /** 
  71.  * 页面开始加载调用的方法 
  72.  * @param view 
  73.  * @param url 
  74.  * @param favicon 
  75.  */  
  76. @Override  
  77. publicvoid onPageStarted(WebView view, String url, Bitmap favicon) {  
  78. Log.d(”zttjiangqq”,“onPageStarted:———–”+url);  
  79. super.onPageStarted(view,url, favicon);  
  80. }  
  81.    
  82. @Override  
  83. publicvoid onReceivedError(WebView view, int errorCode,  
  84. Stringdescription, String failingUrl) {  
  85. super.onReceivedError(view,errorCode, description, failingUrl);  
  86. }  
  87.    
  88. @Override  
  89. publicvoid onScaleChanged(WebView view, float oldScale, float newScale) {  
  90. super.onScaleChanged(view,oldScale, newScale);  
  91. HTML5CustomWebView.this.requestFocus();  
  92. HTML5CustomWebView.this.requestFocusFromTouch();  
  93. }  
  94.    
  95. }  
private classMyWebViewClient extends WebViewClient {/** *加载过程中 拦截加载的地址url * @param view *@param url  被拦截的url * @return */@Overridepublicboolean shouldOverrideUrlLoading(WebView view, String url) {Log.i("zttjiangqq","-------->shouldOverrideUrlLoading url:" + url);//这边因为考虑到之前项目的问题,这边拦截的url过滤掉了zttmall://开头的地址//在其他项目中 大家可以根据实际情况选择不拦截任何地址,或者有选择性拦截if(!url.startsWith("zttmall://")){UrimUri = Uri.parse(url);List<String>browerList = new ArrayList<String>();browerList.add("http");browerList.add("https");browerList.add("about");browerList.add("javascript");if(browerList.contains(mUri.getScheme())) {returnfalse;}else {Intentintent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));intent.addCategory(Intent.CATEGORY_BROWSABLE);//如果另外的应用程序WebView,我们可以进行重用intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);intent.putExtra(Browser.EXTRA_APPLICATION_ID,FDApplication.getInstance().getApplicationContext().getPackageName());try{FDApplication.getInstance().startActivity(intent);returntrue;}catch (ActivityNotFoundException ex) {}}returnfalse;}else{returntrue;}}/** * 页面加载过程中,加载资源回调的方法 * @param view * @param url */@Overridepublicvoid onLoadResource(WebView view, String url) {super.onLoadResource(view,url);Log.i("zttjiangqq","-------->onLoadResource url:" + url);}/** * 页面加载完成回调的方法 * @param view * @param url */@Overridepublicvoid onPageFinished(WebView view, String url) {super.onPageFinished(view,url);Log.i("zttjiangqq","-------->onPageFinished url:" + url);if(isRefresh) {isRefresh= false;}// 加载完成隐藏进度界面,显示WebView内容frame_progress.setVisibility(View.GONE);mContentView.setVisibility(View.VISIBLE);// 关闭图片加载阻塞view.getSettings().setBlockNetworkImage(false);}/** * 页面开始加载调用的方法 * @param view * @param url * @param favicon */@Overridepublicvoid onPageStarted(WebView view, String url, Bitmap favicon) {Log.d("zttjiangqq","onPageStarted:-----------"+url);super.onPageStarted(view,url, favicon);}@Overridepublicvoid onReceivedError(WebView view, int errorCode,Stringdescription, String failingUrl) {super.onReceivedError(view,errorCode, description, failingUrl);}@Overridepublicvoid onScaleChanged(WebView view, float oldScale, float newScale) {super.onScaleChanged(view,oldScale, newScale);HTML5CustomWebView.this.requestFocus();HTML5CustomWebView.this.requestFocusFromTouch();}}

  以上一般使用到得方法已经做了相关的注释。

  最后一步就是使用了,使用起来很简单,创建一个Activity,然后把我们定义的WebView加入到布局然后加载网页即可。如下:

[java] view plain copy
print?
  1. packagecom.chinaztt.fda.html5;  
  2. importandroid.content.Context;  
  3. importandroid.content.Intent;  
  4. importandroid.content.res.Configuration;  
  5. importandroid.net.Uri;  
  6. importandroid.os.Bundle;  
  7. importandroid.view.KeyEvent;  
  8. importandroid.view.MotionEvent;  
  9. importandroid.webkit.DownloadListener;  
  10. importandroid.webkit.JavascriptInterface;  
  11. /** 
  12.  * 当前类注释: 
  13.  * 项目名:FastDev4Android 
  14.  * 包名:com.chinaztt.fda.html5 
  15.  * 作者:江清清 on 15/11/06 08:59 
  16.  * 邮箱:jiangqqlmj@163.com 
  17.  * QQ: 781931404 
  18.  * 公司:江苏中天科技软件技术有限公司 
  19.  */  
  20. importcom.chinaztt.fda.ui.base.BaseActivity;  
  21.    
  22. public classHTML5WebViewCustomAD extends BaseActivity {  
  23. privateHTML5CustomWebView mWebView;  
  24. //http://www.zttmall.com/Wapshop/Topic.aspx?TopicId=18  
  25. privateString ad_url = ”http://www.baidu.com/”;  
  26. private String title=“百度一下你就知道”;  
  27. @Override  
  28. publicvoid onCreate(Bundle savedInstanceState) {  
  29. super.onCreate(savedInstanceState);  
  30. mWebView= new HTML5CustomWebView(this, HTML5WebViewCustomAD.this,title,ad_url);  
  31. mWebView.setDownloadListener(newDownloadListener() {  
  32. @Override  
  33. publicvoid onDownloadStart(String url, String userAgent,  
  34. StringcontentDisposition, String mimetype,  
  35. longcontentLength) {  
  36. Uriuri = Uri.parse(url);  
  37. Intentintent = new Intent(Intent.ACTION_VIEW, uri);  
  38. intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
  39. startActivity(intent);  
  40. }  
  41. });  
  42.         //准备javascript注入  
  43. mWebView.addJavascriptInterface(  
  44. newJs2JavaInterface(),”Js2JavaInterface”);  
  45. if(savedInstanceState != null) {  
  46. mWebView.restoreState(savedInstanceState);  
  47. }else {  
  48. if(ad_url != null) {  
  49. mWebView.loadUrl(ad_url);  
  50. }  
  51. }  
  52. setContentView(mWebView.getLayout());  
  53.    
  54. }  
  55. @Override  
  56. publicvoid onSaveInstanceState(Bundle outState) {  
  57. super.onSaveInstanceState(outState);  
  58. if(mWebView != null) {  
  59. mWebView.saveState(outState);  
  60. }  
  61. }  
  62.    
  63. @Override  
  64. protectedvoid onResume() {  
  65. super.onResume();  
  66. if(mWebView != null) {  
  67. mWebView.onResume();  
  68. }  
  69. }  
  70.    
  71. @Override  
  72. publicvoid onStop() {  
  73. super.onStop();  
  74. if(mWebView != null) {  
  75. mWebView.stopLoading();  
  76. }  
  77. }  
  78. @Override  
  79. protectedvoid onPause() {  
  80. super.onPause();  
  81. if(mWebView != null) {  
  82. mWebView.onPause();  
  83. }  
  84. }  
  85.    
  86. @Override  
  87. protectedvoid onDestroy() {  
  88. super.onDestroy();  
  89. if(mWebView != null) {  
  90. mWebView.doDestroy();  
  91. }  
  92. }  
  93.    
  94. @Override  
  95. publicvoid onConfigurationChanged(Configuration newConfig) {  
  96. super.onConfigurationChanged(newConfig);  
  97. }  
  98.    
  99. @Override  
  100. publicboolean onTouchEvent(MotionEvent event) {  
  101. returnsuper.onTouchEvent(event);  
  102. }  
  103.    
  104. @Override  
  105. publicboolean onKeyDown(int keyCode, KeyEvent event) {  
  106. returnsuper.onKeyDown(keyCode, event);  
  107. }  
  108. @Override  
  109. publicvoid onBackPressed() {  
  110. if(mWebView != null) {  
  111. if(mWebView.canGoBack()){  
  112. mWebView.goBack();  
  113. }else{  
  114. mWebView.releaseCustomview();  
  115. }  
  116. }  
  117. super.onBackPressed();  
  118. }  
  119. /** 
  120.  * JavaScript注入回调 
  121.  */  
  122. publicclass Js2JavaInterface {  
  123. privateContext context;  
  124. privateString TAG = ”Js2JavaInterface”;  
  125. @JavascriptInterface  
  126. publicvoid showProduct(String productId){  
  127. if(productId!=null){  
  128. //进行跳转商品详情  
  129. showToastMsgShort(”点击的商品的ID为:” +productId);  
  130. }else{  
  131. showToastMsgShort(”商品ID为空!”);  
  132. }  
  133. }  
  134. }  
  135. }  
packagecom.chinaztt.fda.html5;importandroid.content.Context;importandroid.content.Intent;importandroid.content.res.Configuration;importandroid.net.Uri;importandroid.os.Bundle;importandroid.view.KeyEvent;importandroid.view.MotionEvent;importandroid.webkit.DownloadListener;importandroid.webkit.JavascriptInterface;/** * 当前类注释: * 项目名:FastDev4Android * 包名:com.chinaztt.fda.html5 * 作者:江清清 on 15/11/06 08:59 * 邮箱:jiangqqlmj@163.com * QQ: 781931404 * 公司:江苏中天科技软件技术有限公司 */importcom.chinaztt.fda.ui.base.BaseActivity;public classHTML5WebViewCustomAD extends BaseActivity {privateHTML5CustomWebView mWebView;//http://www.zttmall.com/Wapshop/Topic.aspx?TopicId=18privateString ad_url = "http://www.baidu.com/";private String title="百度一下你就知道";@Overridepublicvoid onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);mWebView= new HTML5CustomWebView(this, HTML5WebViewCustomAD.this,title,ad_url);mWebView.setDownloadListener(newDownloadListener() {@Overridepublicvoid onDownloadStart(String url, String userAgent,StringcontentDisposition, String mimetype,longcontentLength) {Uriuri = Uri.parse(url);Intentintent = new Intent(Intent.ACTION_VIEW, uri);intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);startActivity(intent);}});        //准备javascript注入mWebView.addJavascriptInterface(newJs2JavaInterface(),"Js2JavaInterface");if(savedInstanceState != null) {mWebView.restoreState(savedInstanceState);}else {if(ad_url != null) {mWebView.loadUrl(ad_url);}}setContentView(mWebView.getLayout());}@Overridepublicvoid onSaveInstanceState(Bundle outState) {super.onSaveInstanceState(outState);if(mWebView != null) {mWebView.saveState(outState);}}@Overrideprotectedvoid onResume() {super.onResume();if(mWebView != null) {mWebView.onResume();}}@Overridepublicvoid onStop() {super.onStop();if(mWebView != null) {mWebView.stopLoading();}}@Overrideprotectedvoid onPause() {super.onPause();if(mWebView != null) {mWebView.onPause();}}@Overrideprotectedvoid onDestroy() {super.onDestroy();if(mWebView != null) {mWebView.doDestroy();}}@Overridepublicvoid onConfigurationChanged(Configuration newConfig) {super.onConfigurationChanged(newConfig);}@Overridepublicboolean onTouchEvent(MotionEvent event) {returnsuper.onTouchEvent(event);}@Overridepublicboolean onKeyDown(int keyCode, KeyEvent event) {returnsuper.onKeyDown(keyCode, event);}@Overridepublicvoid onBackPressed() {if(mWebView != null) {if(mWebView.canGoBack()){mWebView.goBack();}else{mWebView.releaseCustomview();}}super.onBackPressed();}/** * JavaScript注入回调 */publicclass Js2JavaInterface {privateContext context;privateString TAG = "Js2JavaInterface";@JavascriptInterfacepublicvoid showProduct(String productId){if(productId!=null){//进行跳转商品详情showToastMsgShort("点击的商品的ID为:" +productId);}else{showToastMsgShort("商品ID为空!");}}}}

().js注入方法

      仔细查看上面的代码可能大家会发现这样两块地方:

[java] view plain copy
print?
  1. mWebView.addJavascriptInterface(  
  2. newJs2JavaInterface(),”Js2JavaInterface”);  
mWebView.addJavascriptInterface(newJs2JavaInterface(),"Js2JavaInterface");
[java] view plain copy
print?
  1. public classJs2JavaInterface {  
  2. privateContext context;  
  3. privateString TAG = ”Js2JavaInterface”;  
  4. @JavascriptInterface  
  5. publicvoid showProduct(String productId){  
  6. if(productId!=null){  
  7. //进行跳转商品详情  
  8. showToastMsgShort(”点击的商品的ID为:” +productId);  
  9. }else{  
  10. showToastMsgShort(”商品ID为空!”);  
  11. }  
  12. }  
  13. }  
public classJs2JavaInterface {privateContext context;privateString TAG = "Js2JavaInterface";@JavascriptInterfacepublicvoid showProduct(String productId){if(productId!=null){//进行跳转商品详情showToastMsgShort("点击的商品的ID为:" +productId);}else{showToastMsgShort("商品ID为空!");}}}

这边就是js注入回调处理的方法,在这边的实例中是使用http://www.zttmall.com/Wapshop/Topic.aspx?TopicId=18这个地址进行加载网页的时候才会生效,因为这边点击网页图片的时候,html代码中加载js方法,

我们来看一下网页的源代码:


查看源代码我们就知道

[java] view plain copy
print?
  1. mWebView.addJavascriptInterface(  
  2. newJs2JavaInterface(),”Js2JavaInterface”);  
mWebView.addJavascriptInterface(newJs2JavaInterface(),"Js2JavaInterface");

中第二个参数就是在js方法中调用的对象名字,然后注入对象中回调的方法和js方法中的方法一样即可。这样就完成了一次注入点击回调工作,我们的html就可以和原生java代码发生交互了。使用这种方式非常有助于我们的混合开发。

      好了到此重写WebView实现以及js注入的基本使用就讲完了,具体全部代码已经上传到FastDev4Android项目中了。同时欢迎大家去Github站点进行clone或者下载浏览:

https://github.com/jiangqqlmj/FastDev4Android 同时欢迎大家starfork整个开源快速开发框架项目~

尊重原创,转载请注明:From Sky丶清(http://blog.csdn.net/developer_jiangqq) 侵权必究!

关注我的订阅号(codedev123),每天分享移动开发技术(Android/iOS),项目管理以及博客文章!第一时间获取推送文章!


关注我的微博,可以获得更多精彩内容



阅读全文
0 0
原创粉丝点击