Best way to call activity Method with Phonegap 3.0 from js

喜你入骨 提交于 2019-12-04 06:08:18

You can create a custom plugin to call any method from the native side. Create a separate JavaScript file, say customplugin.js, and put this into it:

var CustomPlugin = {};

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

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

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 map the plugins in 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 set up many custom methods conveniently. For more information check the PhoneGap plugin development guide here.

After completing everything from the above answer, you will also need to add the plugin in res/xml/config.xml to make it work

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

before the </plugins> tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!