Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Communication between Android Java and Phonegap Javascript?

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)

like image 382
zorglub76 Avatar asked Apr 28 '10 08:04

zorglub76


1 Answers

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.

like image 58
zorglub76 Avatar answered Sep 21 '22 13:09

zorglub76