java基本常識I/O流應用詳解。本站提示廣大學習愛好者:(java基本常識I/O流應用詳解)文章只能為提供參考,不一定能成為您想要的結果。以下是java基本常識I/O流應用詳解正文
在看懂這篇文章之前起首要有javascript基本。
(1) js挪用android的辦法:
WebView wView;
wView. addJavascriptInterface (Object obj, String interfaceName);
是實例化一個對象,在html的js中挪用,第二個參數是實例化對象的別號,假如要應用這個obj,則在js中應用的名字
就是interfaceName。
public class jsWebDemo extends Activity {
WebView wView;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
wView = (WebView)findViewById(R.id.wv1);
WebSettings wSet = wView.getSettings();
wSet.setJavaScriptEnabled(true);
ProxyBridge pBridge = new ProxyBridge();
wView.addJavascriptInterface(pBridge, "AliansBridge");
wView.loadUrl("file:///android_asset/index.html");
}
private class ProxyBridge {
public int one () {
return 1;
}
}
}
來看一下index.html的內容:
<html>
<mce:script language="javascript"><!--
/* This function is invoked by the activity */
function wave() {
alert("1");
document.getElementById("droid").src="android_waving.png";
alert("2");
}
// --></mce:script>
<body>
<div id="output">Test page.</div>
<a onClick="window.demo.clickOnAndroid()">
<div style="width:100px;
margin:0px auto;
padding:10px;
text-align:center;
border:2px solid #202020;" >
<img id="droid" src="android_normal.png" mce_src="android_normal.png"/><br>
Click me!
</div>
</a>
<input type="submit" value="change to 1" onclick="document.getElementById('output').innerHTML
=AliansBridge.one()" />
</body>
</html>
這裡的AliansBridge等於挪用的JAVA對象。
要留意的是,假如你只要一個辦法須要被js挪用只new一個對象就行:
ProxyBridge pBridge = new ProxyBridge();
wView.addJavascriptInterface(pBridge, "AliansBridge");
假如你須要挪用很多多少個辦法,就要把全部android法式地點的類自己實例化傳遞出來:
wView.addJavascriptInterface(this, "AliansBridge");
(2) android挪用js的辦法:wView.setWebChromeClient (WebChromeClient client)
要用到Handler更新UI,Handler mHandler = new Handler();
mWebView.setWebChromeClient(new MyWebChromeClient());
mWebView.addJavascriptInterface(new Object(){
/**
* 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()");
}
});
}
}, "demo");
同理,在html中必需有一個名為demo的對象挪用clickOnAndroid()辦法。
/**
* 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) {
result.confirm();
return super.onJsAlert(view, url, message, result);
}
}