I believe that it's possible to call Java methods from (PhoneGap) Javascript.
Anyone knows how to do that?? (I know how to do it by changing the source code of PhoneGap, but I'd avoid that)
I finally made it work.
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; } }
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)); } }
In Javascript call window.MyCls methods:
<script> $(function(){ $("#phone").text("My telephone number is: " + window.MyCls.getTelephoneNumber()); }); </script>
Note:
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.
@JavascriptInterface
1.4m articles
1.4m replys
5 comments
57.0k users