android 连续调用js方法,Android的WebView中的JavascriptInterface:对JS的多次调用会导致死锁...
這是我用過(guò)的整個(gè)Java代碼。我將在下面更詳細(xì)地解釋...
public class Test7 extends Activity {
//debug
private final static String TAG = "JSInterface";
private WebView wv;
private class JSInterface {
private WebView wv;
// Variables to manage interfacing with JS
private String returnValue;
private boolean canReadReturnValue;
private Lock lockOnJS;
private Condition condVarOnJS;
public JSInterface (WebView wv) {
this.wv = wv;
this.canReadReturnValue = false;
this.lockOnJS = new ReentrantLock();
this.condVarOnJS = lockOnJS.newCondition();
}
public void setReturnValue(String ret) {
lockOnJS.lock();
returnValue = ret;
canReadReturnValue = true;
condVarOnJS.signal();
lockOnJS.unlock();
Log.d(TAG, "returnValue = " + returnValue);
}
public String getReturnValue() {
Log.d(TAG, "enter in getReturnValue");
lockOnJS.lock();
while (!canReadReturnValue) {
try {
Log.d(TAG, "get wait...");
condVarOnJS.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lockOnJS.unlock();
Log.d(TAG, "returnValue: " + returnValue);
return returnValue;
}
public String getNewString() {
wv.loadUrl("javascript:JSInterface.setReturnValue(createNewString())");
return getReturnValue();
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
wv = (WebView) findViewById(R.id.webView1);
wv.getSettings().setJavaScriptEnabled(true);
wv.addJavascriptInterface(new JSInterface(wv), "JSInterface");
wv.loadUrl("file:///android_asset/prova7.html");
}
public void button1(View v) {
wv.loadUrl("javascript:func('1')");
}
}它似乎工作正常。
你可以看到我有一個(gè)按鈕(我們可以調(diào)用button1),然后單擊它,它會(huì)嘗試執(zhí)行一個(gè)名為func()的JS方法。
public void button1(View v) {
wv.loadUrl("javascript:func('1')");
}在這個(gè)JS方法中,我必須調(diào)用另一個(gè)Java方法。這是代碼:
function func(id) {
document.getElementById(id).innerHTML = JSInterface.getNewString();
}我需要將JSInterface.getNewString()的結(jié)果返回給innerHTML變量。
JSInterface.getNewString()的代碼是這樣的:
public String getNewString() {
wv.loadUrl("javascript:JSInterface.setReturnValue(createNewString())");
return getReturnValue();
}你可以看到我使用方法setReturnValue和getReturnValue來(lái)返回另一個(gè)JS方法返回的值。這是代碼:
function createNewString() {
return "my New String";
}問(wèn)題是,當(dāng)我嘗試設(shè)置returnValue時(shí),函數(shù)createNewString永遠(yuǎn)不會(huì)執(zhí)行!如果我添加一個(gè)console.log()行,我的logCat不顯示任何內(nèi)容!
我不明白為什么會(huì)發(fā)生這種情況。請(qǐng)幫我解決這個(gè)大問(wèn)題!
每一個(gè)幫助將不勝感激
《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的android 连续调用js方法,Android的WebView中的JavascriptInterface:对JS的多次调用会导致死锁...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 2014年江苏省计算机二级c语言考试大纲
- 下一篇: android preference t