Android的Java和Javascript的的PhoneGap之间的通讯? [英] Communication between Android Java and Phonegap Javascript?
问题描述
我相信这是可以调用从(PhoneGap的)Javascript的Java方法。
I believe that it's possible to call Java methods from (PhoneGap) Javascript.
任何人都知道如何做到这一点? (我知道如何通过改变PhoneGap的来源$ C $ C做到这一点,但我想避免这种情况)
Anyone knows how to do that?? (I know how to do it by changing the source code of PhoneGap, but I'd avoid that)
推荐答案
我终于做到了工作。
-
创建要使用一个类方法:
Create a class with methods you want to use:
public class MyClass {
private WebView mAppView;
private DroidGap mGap;
public MyClass(DroidGap gap, WebView view)
{
mAppView = view;
mGap = gap;
}
public String getTelephoneNumber(){
TelephonyManager tm =
(TelephonyManager) mGap.getSystemService(Context.TELEPHONY_SERVICE);
String number = tm.getLine1Number();
return number;
}
}
在您的主要活动添加一个Javascript接口,这个类:
In your main activity add a Javascript interface for this class:
public class Main extends DroidGap
{
private MyClass mc;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.init();
mc = new MyClass(this, appView);
appView.addJavascriptInterface(mc, "MyCls");
super.loadUrl(getString(R.string.url));
}
}
在JavaScript调用window.MyCls方法:
In Javascript call window.MyCls methods:
<script>
$(function(){
$("#phone").text("My telephone number is: " +
window.MyCls.getTelephoneNumber());
});
</script>
注意:
正如注释,对于Android版本4.2及以上, @JavascriptInterface
添加到你想从你的HTML页面来访问方法。 <一href="http://stackoverflow.com/questions/14031635/android-4-2-1-webview-and-javascript-interface-breaks">Reference.
As mentioned in the comment, for Android version 4.2 and above, add @JavascriptInterface
to the method which you want to access from your HTML page. Reference.
这篇关于Android的Java和Javascript的的PhoneGap之间的通讯?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!