Android Java和Phonegap Javascript之间的通信?

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

任何人都知道如何做到这一点? (我知道怎么做,通过改变PhoneGap的源代码,但我会避免)

我终于做到了。

  • 用你想使用的方法创build一个类:

    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接口:

     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方法:

     <script> $(function(){ $("#phone").text("My telephone number is: " + window.MyCls.getTelephoneNumber()); }); </script> 

注意:

正如在评论中提到的,对于Android 4.2及更高版本,将@JavascriptInterface添加到要从HTML页面访问的方法。 参考 。

addJavaScriptInterface(mc, "MyCls") without Gap init() ed可能会导致应用程序addJavascriptInterface() ,最好在addJavascriptInterface()之前添加super.init() addJavascriptInterface()

 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)); } } 

PhoneGap有一个像样的插件API。 你可以通过实现IPlugin接口来使用Java编写插件。 大部分的魔法都在execute()函数中。

 public interface IPlugin { /** * Executes the request and returns PluginResult. * * @param action The action to execute. * @param args JSONArry of arguments for the plugin. * @param callbackId The callback id used when calling back into JavaScript. * @return A PluginResult object with a status and message. */ PluginResult execute(String action, JSONArray args, String callbackId); // ... more ... } 

开始编写插件的最好方法是先编写JavaScript API。 典型的做法是写一个自定义的JavaScript类,然后在JavaScript类的每个方法中编组variables,并调用你使用Phonegap.exec()方法开发的插件。 这是方法签名供您参考。

 /* src/com/phonegap/api/PluginManager.java */ /** * Receives a request for execution and fulfills it by finding the appropriate * Java class and calling it's execute method. * * PluginManager.exec can be used either synchronously or async. In either case, a JSON encoded * string is returned that will indicate if any errors have occurred when trying to find * or execute the class denoted by the clazz argument. * * @param service String containing the service to run * @param action String containt the action that the class is supposed to perform. This is * passed to the plugin execute method and it is up to the plugin developer * how to deal with it. * @param callbackId String containing the id of the callback that is execute in JavaScript if * this is an async plugin call. * @param args An Array literal string containing any arguments needed in the * plugin execute method. * @param async Boolean indicating whether the calling JavaScript code is expecting an * immediate return value. If true, either PhoneGap.callbackSuccess(...) or * PhoneGap.callbackError(...) is called once the plugin code has executed. * * @return JSON encoded string with a response message and status. */ @SuppressWarnings("unchecked") public String exec(final String service, final String action, final String callbackId, final String jsonArgs, final boolean async) 

您还需要注册插件。 您可以通过在自定义JavaScript库底部添加注册码来完成此操作。

在下面的例子中,作者定义了一个javascript BarcodeScanner类,并使用addConstructor方法注册它。

两个步骤在addConstructor中执行:

  1. 在JavaScript中创buildBarcodeScanner的新实例并注册。 这可以通过window.plugins.barcodeScanner在javascript中访问

  2. 使用服务名称注册自定义插件类。 此服务名称作为PhoneGap.exec的第一个参数传入,以便PhoneGap可以实例化Java插件类并调用其上的execute()方法。

样品注册码:

 PhoneGap.addConstructor(function() { /* The following registers an instance of BarcodeScanner in window.plugins.barcodeScanner */ PhoneGap.addPlugin('barcodeScanner', new BarcodeScanner()); /* The following associates a service name BarcodeScanner with a class com.beetight.barcodescanner.BarcodeScanner */ /* The service name is the first argument passed into PhoneGap.exec */ PluginManager.addService("BarcodeScanner","com.beetight.barcodescanner.BarcodeScanner"); }); 

一个更简单的forms:

 public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.init(); super.appView.getSettings().setJavaScriptEnabled(true); super.appView.addJavascriptInterface(this, "MyCls"); super.loadUrl("file:///android_asset/www/login.html"); } 

如果有人使用上面的代码获取nullPointerexception,请先执行super.oncreate(),然后再执行super..init()

 super.onCreate(savedInstanceState); super.init(); 

我在这里find了这个解决scheme: Phonegap Google Group

感谢@ zorglub76的解决scheme….

通过重写Android本地代码中的JavaScript提示符function实现从JavaScript到本地的通信,并且传递的消息非常类似于iOS中使用的消息。 我们曾经使用WebView.addJavascriptInterface将Java对象直接添加到JavaScript沙箱,但是这导致一些设备崩溃与Android 2.3。 为了从本机调用JavaScript,我们目前使用的是WebView.loadUrl(“javascript:…”),但是有一些问题,所以我们很快转移到通过长期XHR连接轮询调用本地HTTP服务器的Java消息队列。

这里描述