您可以创建自定义插件来从本机端调用任何方法。创建一个单独的 JavaScript 文件,例如 customplugin.js,并将其放入其中:
var CustomPlugin = {};
CustomPlugin.callNativeMethod = function() {
cordova.exec(null, null, "CustomPlugin", "callNativeMethod", []);
};
现在,在本机 Java 端,创建一个新类并将其命名为 CustomPlugin.java,然后添加以下内容:
package com.yourpackage;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaInterface;
import org.apache.cordova.api.CordovaPlugin;
import com.yourpackage.MainActivity;
public class CustomPlugin extends CordovaPlugin
{
private static final String TAG = "CustomPlugin";
private CallbackContext callbackContext = null;
private MainActivity activity = null;
/**
* Override the plugin initialise method and set the Activity as an
* instance variable.
*/
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView)
{
super.initialize(cordova, webView);
// Set the Activity.
this.activity = (MainActivity) cordova.getActivity();
}
/**
* Here you can delegate any JavaScript methods. The "action" argument will contain the
* name of the delegated method and the "args" will contain any arguments passed from the
* JavaScript method.
*/
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException
{
this.callbackContext = callbackContext;
Log.d(TAG, callbackContext.getCallbackId() + ": " + action);
if (action.equals("callNativeMethod"))
{
this.callNativeMethod();
}
else
{
return false;
}
return true;
}
private void callNativeMethod()
{
// Here we simply call the method from the Activity.
this.activity.callActivityMethod();
}
}
确保通过添加以下行来映射 config.xml 文件中的插件:
...
<feature name="CustomPlugin">
<param name="android-package" value="com.yourpackage.CustomPlugin" />
</feature>
...
现在要从 index.html 调用插件,您只需调用 JavaScript 方法即可:
CustomPlugin.callNativeMethod();
使用此方法可以让您方便地设置许多自定义方法。有关更多信息,请查看 PhoneGap 插件开发指南here http://docs.phonegap.com/en/2.9.0/guide_plugin-development_android_index.md.html#Developing%20a%20Plugin%20on%20Android.