Best way to call Method function with Phonegap 3.0 from js

I am trying to make a phone call from my index.html to phonegap using the native method from MainActivity.

I am using the phonegap 3.0 platform and Android 4.3. I tried the second answer on this , but it does not work for these versions.

I would like to know what is best for this?

+8
android cordova phone-call
source share
2 answers

You can create your own plugin to call any method from the inside. Create a separate JavaScript file, say customplugin.js, and put it in it:

var CustomPlugin = {}; CustomPlugin.callNativeMethod = function() { cordova.exec(null, null, "CustomPlugin", "callNativeMethod", []); }; 

Now on the side of native Java, create a new class and name it CustomPlugin.java, then add the following:

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

Make sure you insert the plugins into the config.xml file by adding this line:

 ... <feature name="CustomPlugin"> <param name="android-package" value="com.yourpackage.CustomPlugin" /> </feature> ... 

Now, to call the plugin from your index.html, you can simply call your JavaScript method:

 CustomPlugin.callNativeMethod(); 

Using this method will allow you to configure many custom methods. For more information, see the PhoneGap Plugin Development Guide here .

+11
source share

After completing all of the above answer, you will also need to add the plugin to the res / xml / config.xml file for it to work

 <plugin name="PluginName" value="com.namespace.PluginName"/> 

before the tag </plugins>

+2
source share

All Articles