PDA

View Full Version : Calling Native Code in Android from JavaScript using Sencha Touch and PhoneGap 2.2.0



IAmCoder
8 Dec 2012, 1:26 AM
Here is a simple example of how to call native code in Android from within a Sencha Touch application, stripped down to the core elements: http://www.btek.com.au/calling-native-code-from-javascript/.

It took me way longer than it should because I kept getting the “Class not found” error when I pressed the button, which means that something went wrong when trying to load the native class referenced in \res\xml\config.xml. I had it failing because there was no icon in \res\drawable\, believe it or not. And at some point I had an outdated config.xml in the \bin\ and \gen\ directories.

\assets\www\index.html (https://github.com/btek/PhoneGap-Plugin/blob/master/assets/www/index.html)


<html>
<head>
<title>BTek PhoneGap Plugin</title>
<link rel="stylesheet" type="text/css" href="sencha-touch.css"/>
<script type="text/javascript" src="sencha-touch-all.js"></script>
<script type="text/javascript" src="cordova-2.2.0.js"></script>
<script type="text/javascript" src="app.js"></script>
<script type="text/javascript">

function CallNative() {
cordova.exec(SuccessHandler, ErrorHandler, 'BTekPlugin', '', []);
}

function SuccessHandler (result) {
Ext.Msg.alert(result.title, result.details);
}

function ErrorHandler (error) {
alert("Native call failed: " + error);
}
</script>
</head>
<body></body>
</html>

\res\xml\config.xml (https://github.com/btek/PhoneGap-Plugin/blob/master/res/xml/config.xml)

<plugin name="BTekPlugin" value="au.com.BTek.Plugins.BTekPlugin"/>

\src\au\com\BTek\Plugins\BTekPlugin.java (https://github.com/btek/PhoneGap-Plugin/blob/master/src/au/com/BTek/Plugins/BTekPlugin.java)

package au.com.BTek.Plugins;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;


public class BTekPlugin extends Plugin {


public BTekPlugin() {
}


public PluginResult execute(String action, JSONArray args, String callbackId)
{
// Create the response JSON
JSONObject jsonResponse = new JSONObject();
try
{
jsonResponse.put("title", "Hello JavaScript!");
jsonResponse.put("details", "How are you today?");
}
catch(JSONException e)
{
// Raise the error event
this.error(e.getMessage(), callbackId);
}


// Raise the success event
this.success(new PluginResult(PluginResult.Status.OK, jsonResponse), callbackId);


return new PluginResult(PluginResult.Status.OK, "success");
}
}

40660

mitchellsimoens
10 Dec 2012, 6:49 AM
Thanks for sharing!