Android的Java和Javascript的的PhoneGap之间的通讯?通讯、Java、Android、PhoneGap

2023-09-12 00:04:54 作者:人家有伞,我有大头。

我相信这是可以调用从(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接口,这个类:

每个程序员都该学习的5种开发语言

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页面来访问方法。 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.

 
精彩推荐
图片推荐