插件在Phonegap中不起作用

时间:2012-12-15 20:12:51

标签: cordova phonegap-plugins

我正在使用Cordova 2.1.0开发Android插件。

插件代码如下

package org.apache.cordova.example;
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class MyTestPlugin extends Plugin {
  /**
  * 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.
  */
  public PluginResult execute(String action, JSONArray args, String callbackId) {
    try {
      if (action.equals("echo")) {
        String echo = args.getString(0);
        if (echo != null && echo.length() > 0) {
          return new PluginResult(PluginResult.Status.OK, echo);
        } else {
          return new PluginResult(PluginResult.Status.ERROR);
        }
      } else {
        return new PluginResult(PluginResult.Status.INVALID_ACTION);
      }
    } catch (JSONException e) {
      return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
    }
  }
}

HTML / JS代码

<script type="text/javascript" src="cordova-2.1.0.js"></script>
<script type="text/javascript">
  window.echo = function(str, callback) {
    alert('Started');
    cordova.exec(callback, callback, "MyTestPlugin", "echo", [str]);
    alert('The END');
  };
  window.onload = function () {
    alert('1st Step');
    window.echo("echo", function(echoValue) {
      alert(echoValue == "echo"); // should alert true.
    });
    alert('SecondStep');
  };
</script>
</html>

的Config.xml

但是我无法调用插件。有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

deviceredy事件被触发之前,无法调用插件。

window.onload可能 发生在deviceready之前。

http://docs.phonegap.com/en/2.2.0/cordova_events_events.md.html#deviceready