简体   繁体   中英

How to call function in Cordova Plugin

I wrote a simple cordova plugin which displays an alert. JS file: 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

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? And what parameter should i pass to map to successCallback??

according to cordova git for creating plugin see github page you can do it like this

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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