Android 里js 与java相互调用

android里将一个java对象添加成一个js对象只需要调用WebView::addJavascriptInterface()方法;

下面用一个小例子来说明:

Java代码 

1.          public class WebViewDemo extends Activity {  

2.            

3.              private static final String LOG_TAG = "WebViewDemo";  

4.            

5.              private WebView mWebView;  

6.            

7.              private Handler mHandler = new Handler();  

8.            

9.              @Override  

10.           public void onCreate(Bundle icicle) {  

11.               super.onCreate(icicle);  

12.               setContentView(R.layout.main);  

13.               mWebView = (WebView) findViewById(R.id.webview);  

14.         

15.               WebSettings webSettings = mWebView.getSettings();  

16.               webSettings.setSavePassword(false);  

17.               webSettings.setSaveFormData(false);  

18.               webSettings.setJavaScriptEnabled(true);  

19.               webSettings.setSupportZoom(false);  

20.         

21.               mWebView.setWebChromeClient(new MyWebChromeClient());  

22.         

23.               mWebView.addJavascriptInterface(new DemoJavaScriptInterface(), "demo");  

24.         

25.               mWebView.loadUrl("file:///android_asset/demo.html");  

26.           }  

27.         

28.           final class DemoJavaScriptInterface {  

29.         

30.               DemoJavaScriptInterface() {  

31.               }  

32.         

33.               /** 

34.                * This is not called on the UI thread. Post a runnable to invoke 

35.                * loadUrl on the UI thread. 

36.                */  

37.               public void clickOnAndroid() {  

38.                   mHandler.post(new Runnable() {  

39.                       public void run() {  

40.                           mWebView.loadUrl("javascript:wave()");  

41.                       }  

42.                   });  

43.         

44.               }  

45.           }  

46.         

47.           /** 

48.            * Provides a hook for calling "alert" from javascript. Useful for 

49.            * debugging your javascript. 

50.            */  

51.           final class MyWebChromeClient extends WebChromeClient {  

52.               @Override  

53.               public boolean onJsAlert(WebView view, String url, String message, JsResult result) {  

54.                   Log.d(LOG_TAG, message);  

55.                   result.confirm();  

56.                   return true;  

57.               }  

58.                 

59.           }  

60.       }  

 

Html代码 

1.          <html>  

2.              <script language="javascript">  

3.                  /* This function is invoked by the activity */  

4.                  function wave() {  

5.                      alert("1");  

6.                      document.getElementById("droid").src="android_waving.png";  

7.                      alert("2");  

8.                  }  

9.              </script>  

10.           <body>  

11.               <!-- Calls into the javascript interface for the activity -->  

12.               <a onClick="window.demo.clickOnAndroid()"><div style="width:80px;  

13.                   margin:0px auto;  

14.                   padding:10px;  

15.                   text-align:center;  

16.                   border:2px solid #202020;" >  

17.                       <img id="droid" src="android_normal.png"/><br>  

18.                       Click me!  

19.               </div></a>  

20.           </body>  

21.       </html>  

addJavascriptInterface android里的实现:

static void AddJavascriptInterface(JNIEnv *env, jobject obj, jint nativeFramePointer,

        jobject javascriptObj, jstring interfaceName)

{

#ifdef ANDROID_INSTRUMENT

    TimeCounterAuto counter(TimeCounter::NativeCallbackTimeCounter);

#endif

    WebCore::Frame* pFrame = (WebCore::Frame*)nativeFramePointer;

    LOG_ASSERT(pFrame, "nativeAddJavascriptInterface must take a valid frame pointer!");

 

    JavaVM* vm;

    env->GetJavaVM(&vm);

    LOGV("::WebCore:: addJSInterface: %p", pFrame);

 

    // Copied from qwebframe.cpp

    JSC::JSLock lock(false);

    WebCore::JSDOMWindow *window = WebCore::toJSDOMWindow(pFrame);

    JSC::Bindings::RootObject *root = pFrame->script()->bindingRootObject();

    if (window) {

        JSC::Bindings::setJavaVM(vm);

        // Add the binding to JS environment

        JSC::ExecState* exec = window->globalExec();

        JSC::JSObject *addedObject = WeakJavaInstance::create(javascriptObj,

                root)->createRuntimeObject(exec);

        const jchar* s = env->GetStringChars(interfaceName, NULL);

        if (s) {

            // Add the binding name to the window's table of child objects.

            JSC::PutPropertySlot slot;

            window->put(exec, JSC::Identifier(exec, (const UChar *)s,

                    env->GetStringLength(interfaceName)), addedObject, slot);

            env->ReleaseStringChars(interfaceName, s);

            checkException(env);

        }

    }

}

 

在这里细心的朋友已看到这里的js与java相互调用都是不带参数的,那它可以带参数吗?可以带哪些类型的参数,有什么规范?这些将在下回分析!

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值