Behavioural Technology Group | BTek

Latest Blogs from BTek

Calling Native Code from JavaScript using Sencha Touch and PhoneGap 2.2.0

As part of the mobile sensing framework, I needed to call native code from JavaScript in Sencha Touch through PhoneGap. But ever since Cordova 1.9.0 was released, none of the plugin examples seem to work anymore. So here is one that does.

The cordova.exec() function looks up the third parameter (‘BTekPlugin’) in \res\xml\config.xml to get the full namespace of the native class “” and then raises the success or error event handler.


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


<plugin name="BTekPlugin" value=""/>



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

Here is the final product – the button calls the cordova.exec() function and raises the success event:

In case you have a run-in with the infamous “Class not found” error message; it 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.

Download the APK: PhoneGap Plugin or browse the source code

Social Share Counters

Posted in: mobile, mobile sensing, phonegap, sencha touch

Leave a Comment: (2) →

1 Comment

  1. Adam Goodrich December 7, 2012

    Wow – awesome article Michael!


Leave a Comment