Android與javaScript的交互


WebView與js的交互包含兩方面,一是在html中通過js調用java代碼;二是在安卓java代碼中調用js。

一、html中通過js調用java代碼

js中調用java代碼其實就記住一點,WebView設置一個和js交互的接口(這里的接口是一般的意思,不是java中接口的含義),這個接口其實就是一個一般的類,同時為這個接口取一個別名。這個過程如下:
mWebView.addJavaScriptInterface(new DemoJavaScriptInterface(),"demo");
new DemoJavaScriptInterface()就是這個接口,demo就是這個接口的別名。
上面的代碼執行后在html中js就能通過別名(這里是“demo”)來調用DemoJavaScriptInterface類中的任何方法了。
如果我們想讓html中的一個button點擊之后調用java中的函數可以這樣:
<input type="button" value="click me" onclick="window.demo.clickOnAndroid()"/>
但是因為安全問題,在Android4.2中(如果應用的android:targetSdkVersion為17+)JS只能訪問帶有@javaScriptInterface注解的java函數,所以開發版本較高的時候,在需要被調用的函數前加上這個注解。4.2以下為了安全盡量不要調用addJavascriptInterface,需要另謀他法。

下面是google官方給的實例:
WebViewDemo.java

[代碼]java代碼:

?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.google.android.webviewdemo;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
/**
  * Demonstrates how to embed a WebView in your activity. Also demonstrates how
  * to have javascript in the WebView call into the activity, and how the activity
  * can invoke javascript.
  * <p>
  * In this example, clicking on the android in the WebView will result in a call into
  * the activities code in {@link DemoJavaScriptInterface#clickOnAndroid()}. This code
  * will turn around and invoke javascript using the {@link WebView#loadUrl(String)}
  * method.
  * </p><p>
  * Obviously all of this could have been accomplished without calling into the activity
  * and then back into javascript, but this code is intended to show how to set up the
  * code paths for this sort of communication.
  *
  */
public class WebViewDemo extends Activity {
     private static final String LOG_TAG = "WebViewDemo" ;
     private WebView mWebView;
     private Handler mHandler = new Handler();
     @Override
     public void onCreate(Bundle icicle) {
         super .onCreate(icicle);
         setContentView(R.layout.main);
         mWebView = (WebView) findViewById(R.id.webview);
         WebSettings webSettings = mWebView.getSettings();
         webSettings.setSavePassword( false );
         webSettings.setSaveFormData( false );
         webSettings.setJavaScriptEnabled( true );
         webSettings.setSupportZoom( false );
         mWebView.setWebChromeClient( new MyWebChromeClient());
         mWebView.addJavascriptInterface( new DemoJavaScriptInterface(), "demo" );
         mWebView.loadUrl( "file:///android_asset/demo.html" );
     }
     final class DemoJavaScriptInterface {
         DemoJavaScriptInterface() {
         }
         /**
          * This is not called on the UI thread. Post a runnable to invoke
          * loadUrl on the UI thread.
          */
         public void clickOnAndroid() {
             mHandler.post( new Runnable() {
                 public void run() {
                     mWebView.loadUrl( "javascript:wave()" );
                 }
             });
         }
     }
     /**
      * Provides a hook for calling "alert" from javascript. Useful for
      * debugging your javascript.
      */
     final class MyWebChromeClient extends WebChromeClient {
         @Override
         public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
             Log.d(LOG_TAG, message);
             result.confirm();
             return true ;
         }
     }
}</p>

 

demo.html

[代碼]xml代碼:

?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
< html >
     < script language = "javascript" >
         /* This function is invoked by the activity */
         function wave() {
             alert("1");
             document.getElementById("droid").src="android_waving.png";
             alert("2");
         }
     </ script >
     < body >
         <!-- Calls into the javascript interface for the activity -->
         < a onClick = "window.demo.clickOnAndroid()" >
             < div style="width:80px;
                 margin:0px auto;
                 padding:10px;
                 text-align:center;
                 border:2px solid #202020;" >
                 < img id = "droid" src = "android_normal.png" />< br >
                 Click me!
             </ div >
         </ a >
     </ body >
</ html >

 

main.xml

[代碼]xml代碼:

?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
< LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
     android:orientation = "vertical"
     android:layout_width = "fill_parent"
     android:layout_height = "fill_parent"
     >
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      
     < TextView
         android:layout_width = "fill_parent"
         android:layout_height = "wrap_content"
         android:text = "@string/intro"
         android:padding = "4dip"
         android:textSize = "16sp"
         />
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      
     < WebView
         android:id = "@+id/webview"
         android:layout_width = "fill_parent"
         android:layout_height = "0dip"
         android:layout_weight = "1"
         />
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
</ LinearLayout >

 

Android調用js

調用webview頁面內的js方法,調用形式:
mWebView.loadUrl("javascript:wave()");
其中wave()是js中的一個方法,當然你可以把這個方法改成其他的方法,也就是android調用其他的方法。但java不能直接獲取Js方法的返回結果。

小結

具體交互流程如下:

  • 點擊圖片,則在js端直接調用android上的方法clickOnAndroid();
  • clickOnAndroid()方法(利用線程)調用js的方法。
  • 被調用的js直接控制html。

利用webView的這種方式在有些時候UI布局就可以轉成相應的html代碼編寫了,而html布局樣式之類有DW這樣強大的工具,而且網上很多源碼,很多代碼片。在UI和視覺效果上就會節省很多時間,重復發明輪子沒有任何意義。

交互結果

Android Webview中Java調用Js方法很容易,loadUrl("javascript:isOk()")就可以調用isOk這個Js方法,但不能直接獲取Js方法的返回結果。
1.傳統的方法中,Js獲取Java信息可以采用如下方式:

[代碼]java代碼:

?
1
2
3
4
5
6
7
class JsObject {
       @JavascriptInterface
       public String toString() { return "injectedObject" ; }
    }
webView.addJavascriptInterface( new JsObject(), "injectedObject" );
webView.loadData( "" , "text/html" , null );
webView.loadUrl( "javascript:alert(injectedObject.toString())" );

 

2.Java獲取Js信息(如通過Js獲取網頁源代碼)可以這樣:

[代碼]java代碼:

?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;
 
public class HtmlSource extends Activity {
     private WebView webView;
 
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super .onCreate(savedInstanceState);
         setContentView(R.layout.main);
         webView = (WebView)findViewById(R.id.webview);
         webView.getSettings().setJavaScriptEnabled( true );
         webView.addJavascriptInterface( new InJavaScriptLocalObj(), "local_obj" );
         webView.setWebViewClient( new MyWebViewClient());
         webView.loadUrl( "http://www.cnblogs.com/hibraincol/" );
     }
 
 
    final class MyWebViewClient extends WebViewClient{ 
         public boolean shouldOverrideUrlLoading(WebView view, String url) {  
             view.loadUrl(url);  
             return true ;  
        
         public void onPageStarted(WebView view, String url, Bitmap favicon) {
             Log.d( "WebView" , "onPageStarted" );
             super .onPageStarted(view, url, favicon);
         }   
         public void onPageFinished(WebView view, String url) {
             Log.d( "WebView" , "onPageFinished " );
             view.loadUrl( "javascript:window.local_obj.showSource(''+" +
                 "document.getElementsByTagName('html')[0].innerHTML+'');" );
             super .onPageFinished(view, url);
         }
     }
 
     final class InJavaScriptLocalObj {
 
         public void showSource(String html) {
             Log.d( "HTML" , html);
         }
     }
}

 

當網頁中有超鏈接跳轉時,將會調用WebClient的shouldOverrideUrlLoading方法,若設置 WebViewClient 且該方法返回 true,則說明由應用的代碼處理該 url,WebView 不處理,就可以達到攔截跳轉的效果。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM