Phonegap natives Android Plugin erstellen Tutorial


With PhoneGap native code can trigger out of Javascript with the following code:

//onDeviceReady          

cordova.exec( success, fail, "UploadImage", "nativeAction", ["success"]);    

            function success (result) {    
                alert("SUCCESS: \r\n"+result );
                }
            function fail (error) {    
                alert("ERROR: \r\n"+error );
                }

This code calls the class Upload Image execute the function with parameter action = 'native action’ and one JsonString(!) data = “['success']” on. Data can be used for this data to be passed to Java:

import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;

public class UploadImage extends Plugin {
    public static final String NATIVE_ACTION_STRING="nativeAction";       
    public static final String SUCCESS_PARAMETER="success";
    @Override
    public PluginResult execute(String action, JSONArray data, String callbackId) {
        Log.d("HelloPlugin", "Hello, this is a native function called from PhoneGap/Cordova!");             
        //only perform the action if it is the one that should be invoked              
        if (NATIVE_ACTION_STRING.equals(action)) {                    
            String resultType = null;                    
        try {                          
            resultType = data.getString(0);                    }                    
        catch (Exception ex) {                          
            Log.d("HelloPlugin", ex.toString());                    }                    
        if (resultType.equals(SUCCESS_PARAMETER)) {                          
            return new PluginResult(PluginResult.Status.OK, "Yay, Success!!!");                    
            }                    
        else {                          
            return new PluginResult(PluginResult.Status.ERROR, "Oops, Error :( ");                    
            }              
        }                
        return null;
    }
}

In addition, the plug-in must res/xml/config.xml be entered:

<plugin name="UploadImage" value="de.sv.foo.plugin.UploadImage"/>

 

The output should be:

"SUCCESS: Yay, Success!!!"