简体   繁体   English

如何在Cordova插件中调用函数

[英]How to call function in Cordova Plugin

I wrote a simple cordova plugin which displays an alert. 我写了一个简单的cordova插件来显示警报。 JS file: alert.js JS文件:alert.js

module.exports = {
alert: function(title, message, buttonLabel, successCallback) {
cordova.exec(successCallback,
             null, // No failure callback
             "Alert",
             "alert",
             [title, message, buttonLabel]);
    }
};

Java File: Alert.java Java档案:Alert.java

package com.acme.plugin.alert;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Alert extends CordovaPlugin {
  protected void pluginInitialize() {
  }

  public boolean execute(String action, JSONArray args, CallbackContext callbackContext) 
      throws JSONException {
    if (action.equals("alert")) {
      alert(args.getString(0), args.getString(1), args.getString(2), callbackContext);
      return true;
    }
    return false;
  }

  private synchronized void alert(final String title, 
                                  final String message, 
                                  final String buttonLabel, 
                                  final CallbackContext callbackContext) {
    new AlertDialog.Builder(cordova.getActivity())
    .setTitle(title)
    .setMessage(message)
    .setCancelable(false)
    .setNeutralButton(buttonLabel, new AlertDialog.OnClickListener() {
      public void onClick(DialogInterface dialogInterface, int which) {
        dialogInterface.dismiss();
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 0));
      }
    })
    .create()
    .show();
  }
}

How do I call the alert function of alert.js from another js? 如何从另一个js调用alert.js的警报功能? And what parameter should i pass to map to successCallback?? 我应该传递什么参数来映射到successCallback?

according to cordova git for creating plugin see github page you can do it like this 根据cordova git创建插件, 请参见github页面,您可以这样做

Add the following code to wherever you need to call the plugin functionality: 将以下代码添加到需要调用插件功能的任何地方:

 ‍‍‍cordova.plugins.<PluginName>.<method>();

where <PluginName> is your plugin name and <method> is your method. 其中<PluginName>是您的插件名称,而<method>是您的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM