本文介绍了Android Java和Phonegap Javascript之间的通信?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我相信可以从 (PhoneGap) Javascript 调用 Java 方法.

I believe that it's possible to call Java methods from (PhoneGap) Javascript.

有人知道怎么做吗??(我知道如何通过更改 PhoneGap 的源代码来实现,但我会避免这样做)

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 页面访问的方法中.参考.

    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和Phonegap Javascript之间的通信?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    07-29 13:15