【FastDev4Android框架開發】重寫WebView網頁加載以及JavaScript注入詳解(二十三)

轉載請標明出處: 

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

().前言:   

         【好消息】個人網站已經上線運行,後面博客以及技術乾貨等精彩文章會同步更新,請大家關注收藏:http://www.lcode.org

       今天我們來學習一下重寫WebView組件來實現網頁的加載,以及我們平時APP開發中經常使用的JS注入,jsJava相互調用的問題來重點講解一下。如果大家都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容器佈局,如下:

  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初始化設置如下:

  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);  //開啓javascript
webSettings.setDomStorageEnabled(true);  //開啓DOM
webSettings.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進行相關設置處理

  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;
@Override
publicvoid 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);
}

@Override
publicvoid 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
 */
@Override
publicvoid onReceivedTitle(WebView view, String title) {
Log.d("zttjiangqq", "當前網頁標題爲:" + title);
wv_tv_title.setText(title);
}

/**
 * 網頁加載進度回調
 * @param view
 * @param newProgress
 */
@Override
publicvoid onProgressChanged(WebView view, int newProgress) {
// 設置進行進度
((Activity)mContext).getWindow().setFeatureInt(
Window.FEATURE_PROGRESS,newProgress * 100);
webview_tv_progress.setText("正在加載,已完成" +newProgress + "%...");
webview_tv_progress.postInvalidate(); //刷新UI
Log.d("zttjiangqq", "進度爲:" + newProgress);
}

@Override
publicboolean onJsAlert(WebView view, String url, String message,
JsResultresult) {
returnsuper.onJsAlert(view, url, message, result);

}
}

  2.6.WebViewClient進行相關設置處理

  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
 */
@Override
publicboolean 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
 */
@Override
publicvoid onLoadResource(WebView view, String url) {
super.onLoadResource(view,url);
Log.i("zttjiangqq","-------->onLoadResource url:" + url);
}
/**
 * 頁面加載完成回調的方法
 * @param view
 * @param url
 */
@Override
publicvoid 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
 */
@Override
publicvoid onPageStarted(WebView view, String url, Bitmap favicon) {
Log.d("zttjiangqq","onPageStarted:-----------"+url);
super.onPageStarted(view,url, favicon);
}

@Override
publicvoid onReceivedError(WebView view, int errorCode,
Stringdescription, String failingUrl) {
super.onReceivedError(view,errorCode, description, failingUrl);
}

@Override
publicvoid onScaleChanged(WebView view, float oldScale, float newScale) {
super.onScaleChanged(view,oldScale, newScale);
HTML5CustomWebView.this.requestFocus();
HTML5CustomWebView.this.requestFocusFromTouch();
}

}

  以上一般使用到得方法已經做了相關的註釋。

  最後一步就是使用了,使用起來很簡單,創建一個Activity,然後把我們定義的WebView加入到佈局然後加載網頁即可。如下:

  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.  * 郵箱:[email protected] 
  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
 * 郵箱:[email protected]
 * QQ: 781931404
 * 公司:江蘇中天科技軟件技術有限公司
 */
importcom.chinaztt.fda.ui.base.BaseActivity;

public classHTML5WebViewCustomAD extends BaseActivity {
privateHTML5CustomWebView mWebView;
//http://www.zttmall.com/Wapshop/Topic.aspx?TopicId=18
privateString ad_url = "http://www.baidu.com/";
private String title="百度一下你就知道";
@Override
publicvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mWebView= new HTML5CustomWebView(this, HTML5WebViewCustomAD.this,title,ad_url);
mWebView.setDownloadListener(newDownloadListener() {
@Override
publicvoid 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());

}
@Override
publicvoid onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if(mWebView != null) {
mWebView.saveState(outState);
}
}

@Override
protectedvoid onResume() {
super.onResume();
if(mWebView != null) {
mWebView.onResume();
}
}

@Override
publicvoid onStop() {
super.onStop();
if(mWebView != null) {
mWebView.stopLoading();
}
}
@Override
protectedvoid onPause() {
super.onPause();
if(mWebView != null) {
mWebView.onPause();
}
}

@Override
protectedvoid onDestroy() {
super.onDestroy();
if(mWebView != null) {
mWebView.doDestroy();
}
}

@Override
publicvoid onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}

@Override
publicboolean onTouchEvent(MotionEvent event) {
returnsuper.onTouchEvent(event);
}

@Override
publicboolean onKeyDown(int keyCode, KeyEvent event) {
returnsuper.onKeyDown(keyCode, event);
}
@Override
publicvoid onBackPressed() {
if(mWebView != null) {
if(mWebView.canGoBack()){
mWebView.goBack();
}else{
mWebView.releaseCustomview();
}
}
super.onBackPressed();
}
/**
 * JavaScript注入回調
 */
publicclass Js2JavaInterface {
privateContext context;
privateString TAG = "Js2JavaInterface";
@JavascriptInterface
publicvoid showProduct(String productId){
if(productId!=null){
//進行跳轉商品詳情
showToastMsgShort("點擊的商品的ID爲:" +productId);
}else{
showToastMsgShort("商品ID爲空!");
}
}
}
}

().js注入方法

      仔細查看上面的代碼可能大家會發現這樣兩塊地方:

  1. mWebView.addJavascriptInterface(  
  2. newJs2JavaInterface(),”Js2JavaInterface”);  
mWebView.addJavascriptInterface(
newJs2JavaInterface(),"Js2JavaInterface");
  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";
@JavascriptInterface
publicvoid showProduct(String productId){
if(productId!=null){
//進行跳轉商品詳情
showToastMsgShort("點擊的商品的ID爲:" +productId);
}else{
showToastMsgShort("商品ID爲空!");
}
}
}

這邊就是js注入回調處理的方法,在這邊的實例中是使用http://www.zttmall.com/Wapshop/Topic.aspx?TopicId=18這個地址進行加載網頁的時候纔會生效,因爲這邊點擊網頁圖片的時候,html代碼中加載js方法,

我們來看一下網頁的源代碼:


查看源代碼我們就知道

  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),項目管理以及博客文章!第一時間獲取推送文章!


關注我的微博,可以獲得更多精彩內容



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章