Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android Apps
GitHub logo Twitter logo OReilly Book Cover Art
PhoneGap (Android) Accessing your java files from javascriptBack to Android Cookbook Home | Up to Chapter: Other Programming Languages

Author: Shraddha Shravagi ('sshraddha')
In Published Edition? No
FormatLanguage: WikiFormat

PhoneGap (Android) Accessing your java files from javascript


You need to access your methods from Activity.java in JavaScript


If you are using PhoneGap and developing for a platform independent application then you will have your functions in Javascript. But if you want your javascript file to talk with Activity.java then here's how you do it.


Your Android project will contain all your Javascript and Java files as discussed in 3542.

Add following code to the onCreate() method of your Activity

	super.appView.addJavascriptInterface(new HelperClass(),

Create the HelperClass class:

public int state = 0;  
public class HelperClass{  
// All the methods that you want to expose to Javascript will go here.  
public int getState(){  
    return this.state;  
}//end of class

Now in your javascript file you can access the method getState() as follows:

int state = window.mActivityInterface.getState();

See Also