標(biāo)題: android與javascript交互 [打印本頁(yè)]

作者: 51hei小林    時(shí)間: 2016-9-25 11:04
標(biāo)題: android與javascript交互
Android與Javascript交互主要是使用的WebView。

關(guān)于WebView,一般涉及到2個(gè)類(lèi):WebChromeClient 和 WebViewClient 。
開(kāi)發(fā)的大致流程為(摘自Android developer):
A WebView has several customization points where you can add your own behavior. These are:
Creating and setting a WebChromeClient subclass. This class is called when something that might impact a browser UI happens, for instance, progress updates and JavaScript alerts are sent here (see Debugging Tasks).
Creating and setting a WebViewClient subclass. It will be called when things happen that impact the rendering of the content, eg, errors or form submissions. You can also intercept URL loading here (via shouldOverrideUrlLoading()).
Modifying the WebSettings, such as enabling JavaScript with setJavaScriptEnabled().
Injecting Java objects into the WebView using the addJavascriptInterface(Object, String) method. This method allows you to inject Java objects into a page's JavaScript context, so that they can be accessed by JavaScript in the page.
好了,廢話不多說(shuō),上Demo。
此demo完成了Android與Javascript交互的基礎(chǔ)功能,并用json字符串進(jìn)行了值傳遞。
秉持一貫的風(fēng)格,知識(shí)內(nèi)容都在代碼注釋中,這樣方便以后復(fù)習(xí)。(布局就不貼了,比較簡(jiǎn)單)
整個(gè)工程結(jié)構(gòu)比較簡(jiǎn)單:



首先是這個(gè)jsdroid.html文件的界面(貼界面其實(shí)有點(diǎn)2 --。


html代碼比較簡(jiǎn)單:

[html] view plain copy
print?




其中,id為“btn_pmt”的button,監(jiān)聽(tīng)器設(shè)置的是調(diào)用Android中的方法。

好了,上最重要的,android端實(shí)現(xiàn)的代碼。

[java] view plain copy
print?





這只是粗略地學(xué)習(xí)了下android和Javascript的交互,后面的,還需要繼續(xù)深入研究下。

最終在手機(jī)上跑的效果圖:



Demo的下載地址:
http://download.csdn.net/detail/singleton1900/5238800









歡迎光臨 (http://www.torrancerestoration.com/bbs/) Powered by Discuz! X3.1