8

I am new to PhoneGap and I am able to implement the basic app with PhoneGap, now to enhance it further, I want to connect PhoneGap with Android Activities, basically what I plan is to call startActivity() method using a javascript function.

I tried Communication between Android Java and Phonegap Javascript?

but I failed to call an activity, causing force close error. Do help me out, awaiting a reply!

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Aditya Gaykar
  • 470
  • 1
  • 5
  • 10

4 Answers4

26

Any Java Native code call be called without using any plugin as following.

Follow The following Steps.

  1. Replace the following code with your existing DroidGap Activity.

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.init(); // Calling this is necessary to make this work
        appView.addJavascriptInterface(this, "MainActivity");
    
        /* "this" points the to the object of the current activity. "MainActivity" is used to refer "this" object in JavaScript as in Step 3. */
    
        super.loadUrl("file:///android_asset/www/index.html");
    }
    
  2. Add the custom function in current (this) activity as following.

    public void customFunctionCalled() {
        Log.e("Custom Function Called", "Custom Function Called");
    }
    
  3. Now call this function from your HTML/JavaScript code as following.

    <script type="text/javascript">
        function callNewActivity() {
            window.MainActivity.customFunctionCalled();
        }
    </script>
    

This will call customFunctionCalled() in MainActivity.

Tested Environment Eclipse - 3.7.2 Android 2.2 Emulator PhoneGap - 2.0.0

Please provide your comments here to improve blogs post. http://phonegapexplorers.blogspot.in/2012/08/call-native-java-code-phonegap-android.html

Sthe
  • 2,575
  • 2
  • 31
  • 48
AvtarSingh Suchariya
  • 1,992
  • 1
  • 20
  • 25
  • I was using it for a long time. But recently having some problem with android 4.2.2. Learn from web that it's working correctly with sdk>=17. Can you please tell me the changes I need to work with sdk>=17?? – AtanuCSE Jun 15 '14 at 10:32
  • @AvtarSingh Suchariya Hy I followed your tutorial but I get: 07-08 23:44:04.845: E/Web Console(25296): Uncaught TypeError: Object [object Object] has no method 'customFunctionCalled' at file:///android_asset/www/js/index.js:31 Why is that? I heared there must be some modifications if the target SDK is 17 or more (I think its my case). But I don't know what are those. Can you please help me? – Alex Stanese Jul 08 '14 at 20:49
  • @AtanuCSE hy man have you figured outhow to use the script with sdk>=17? Can you please tell me how to do it? – Alex Stanese Jul 08 '14 at 20:53
  • @AlexStanese Nope, As I wasn't using any heavy native feature, I just lowered my target SDK to 16 to get it work for now. – AtanuCSE Jul 08 '14 at 21:06
  • phh ok... if anyone know how to make it work on SDK >=17 please let us know! – Alex Stanese Jul 08 '14 at 21:09
  • 1
    @AtanuCSE I GOT IT!!! Just add "@JavascriptInterface" before "public void customFunctionCalled() {" – Alex Stanese Jul 08 '14 at 21:15
2

Its hard without knowing more about what you're trying to do exactly, but going down the road of writing a plugin is probably the way to go. Check out;

http://smus.com/android-phonegap-plugins

This plugin might work for you as is, or give you good pointers in how to do this yourself.

Mike P
  • 2,797
  • 2
  • 21
  • 25
0

I try what you trying to do before, with updates on phonegap to version 2.0.0 and upward the best way to do is with plugin. This is the js on phonegap within assets folder. Make sure to construct div element with id "nativecall" and a sample button to do detect it.Be sure to watch LogCat to check error messages.

    window.echo = function(str, callback) {
    cordova.exec(callback, function(err) {
        callback('Nothing to echo.');
    }, "Echo", "echo", [str]);
};

var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicity call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
    },
    // Update DOM on a Received Event
    receivedEvent: function() {

        var abiter = $('#nativecall').html();

            $("#abutton").click(function () {
                    window.echo(abiter, function(echoValue) {
                    alert(echoValue = abiter); // should alert true.
                });
            });


    }
};

app.initialize();

on src add new class method with service name "Echo".

    package org.apache.cordova.plugin;

import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.plugin.AndroidActivities;
import org.apache.cordova.api.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;

/**
 * This class echoes a string called from JavaScript.
 */
public class Echo extends CordovaPlugin {
    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if (action.equals("echo")) {
            String message = args.getString(0);
            new AndroidPublicFunction(message); //call function from AndroidActivities
            this.echo(message, callbackContext);
            return true;
        }
        return false;
    }

    private void echo(String message, CallbackContext callbackContext) {
        if (message != null && message.length() > 0) { 
            callbackContext.success(message);
        } else {
            callbackContext.error("Expected one non-empty string argument.");
        }
    }
}
syarul
  • 2,161
  • 2
  • 20
  • 22
0

Try creating plugins, here are some plugins example https://github.com/phonegap/phonegap-plugins

Jaiprakash Soni
  • 4,100
  • 5
  • 36
  • 67