Tuesday, May 24, 2011

Getting an Access of Android Java Code to a PhoneGap JavaScript.

PhoneGap Provides a standard set of functions available in PhoneGap docs to access the internal Device Details like the list of the phone numbers, access to camera etc.

Apart from this standard functions, if our requirements extends then these available functions, then we need to create our own custom logical functions which access the internal device hardware details like 'imei' number etc or to apply some custom logic or validate the data and then make it available to PhoneGap, then this article helps to do the same.

Though PhoneGap provides the 'imei' number through the standard function 'device.uuid' but in Android 2.1, it is still an issue. For such cases we need to take the help of the Native Android Java Code and then make it accessible to PhoneGap, here is how we will be doing the same.

Following example is of getting the device's 'imei' number through the Android's TelephonyManager class and then make it available to PhoneGap JavaScript:

Create a custom Class as follows:

import com.phonegap.DroidGap;
import android.content.Context;
import android.telephony.TelephonyManager;
import android.webkit.WebView;


public class CustomNativeAccess {
    private WebView mAppView;
    private DroidGap mGap;
    public CustomNativeAccess(DroidGap gap, WebView view)
    {
        mAppView = view;
        mGap = gap;
    }   
    public String getImeiNumber(){
    TelephonyManager tm = (TelephonyManager) mGap.getSystemService(Context.TELEPHONY_SERVICE);
        String imeiId = tm.getDeviceId();      
        return imeiId;
    }
}

Function 'getImeiNumber()' retuns the 'imei' number of the device and the same function we will be using in PhoneGap Javascript.

Now Comming to the main Activity Class of the Application:


import com.phonegap.*;
public class MyActivity extends DroidGap {
    /** Called when the activity is first created. */
CustomNativeAccess cna;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);      
        super.init();    
        cna = new CustomNativeAccess(this, appView);    
        appView.addJavascriptInterface(cna, "CustomNativeAccess");      
        super.loadUrl("file:///android_asset/www/index.html");
    }
}

'appView' is an built in variable of DroidGap and it is initialized through the call 'super.init();'.
'appView.addJavascriptInterface' adds all the function of the specified class i.e. 'CustomNativeAccess' here in example, and makes it accessible in the JavaScript in PhoneGap Application.

Finally, to get the access in JavaScript,


var imeiNumber = window.CustomNativeAccess.getImeiNumber();

returns the valid 'imei' number.

I hope this article is useful for getting the Native Android Java Code Access to the PhoneGap's JavaScript.

~ Mayuri

20 comments:

Luis Zandonadi Bissoli said...

Good Article!!! Congratulations.

Mayuri Ruparel said...

Thanks!

hit said...

Good Post for all who want to learn Android who is new for android, very Help full.

Great.....

Mayuri Ruparel said...

Thanks

kumarpsk said...

Hello mam;
I try the following example but i cant get imei number added any permission in android AndroidManifest.xml and one more question mam How to i call the Activity through the phonegap please help me mam

bhargavi joshi said...

Hi,
This is very good post.
Like this can any one know how to access "Native application" (build in Android)
This Native application shows turn by turn road from current location on Google map.

sikamedia said...

I tried your code and tested it with Phonegap 1.2 with android emulator, it gives errors from log:



D/szipinf ( 578): Initializing inflate state
D/szipinf ( 578): Initializing zlib to inflate
D/szipinf ( 578): Initializing inflate state
D/szipinf ( 578): Initializing zlib to inflate
W/dalvikvm( 578): JNI WARNING: jarray 0x40582ed8 points to non-array object (Ljava/lang/String;)
I/dalvikvm( 578): "WebViewCoreThread" prio=5 tid=9 NATIVE
I/dalvikvm( 578): | group="main" sCount=0 dsCount=0 obj=0x4051c2a8 self=0x2a0878
I/dalvikvm( 578): | sysTid=587 nice=0 sched=0/0 cgrp=default handle=2754992
I/dalvikvm( 578): | schedstat=( 1726910419 1284239754 135 )
I/dalvikvm( 578): at android.webkit.LoadListener.nativeFinished(Native Method)
I/dalvikvm( 578): at android.webkit.LoadListener.nativeFinished(Native Method)
I/dalvikvm( 578): at android.webkit.LoadListener.tearDown(LoadListener.java:1200)
I/dalvikvm( 578): at android.webkit.LoadListener.handleEndData(LoadListener.java:721)
I/dalvikvm( 578): at android.webkit.LoadListener.handleMessage(LoadListener.java:219)
I/dalvikvm( 578): at android.os.Handler.dispatchMessage(Handler.java:99)
I/dalvikvm( 578): at android.os.Looper.loop(Looper.java:123)
I/dalvikvm( 578): at android.webkit.WebViewCore$WebCoreThread.run(WebViewCore.java:629)
I/dalvikvm( 578): at java.lang.Thread.run(Thread.java:1019)
I/dalvikvm( 578):
E/dalvikvm( 578): VM aborting


I guess you have to do this with PhoneGap plugin framework for this purpose with the latest PhoneGap release.

Tejas Shah said...

It's good article..:)
very Help full to all new members of phone-gap and android..
Thanks a lot..:)

zionz said...

Hi,

Is it possiable to receive the project source code?

Thanks

Rhyn said...

Is it possible to make a 'Void' method instead of Return something?
like :
public void call(String phoneNumber){}

Thanks

madhulika reddy tatiparthi said...

Hi good post but what if have 2 java classes does the intent will work?

madhulika reddy tatiparthi said...
This comment has been removed by the author.
Simon MacDonald said...

You shouldn't use addJavaScriptInterface directly as:

a) it is broken on the 2.3 emulator
b) it causes problems with the keyboard being shown/hidden

It is better to use the actual Plugin API that PhoneGap provides.

http://docs.phonegap.com/en/2.0.0/guide_plugin-development_index.md.html#Plugin%20Development%20Guide

Uma Mahesh said...

then what we have to write in index.html file while loading

Uma Mahesh said...

then what we have to write in index.html file while loading

Ankit Shandilya said...

is there any way to Getting an Access of Android Java Code to a Rhodes HTML5.

Tushar Rungta said...

Hi Mayuri,

Can you tell me what is the use of using WebView Code here because the code runs fine without it also

Please reply .... :(

Glau said...

I'm trying to do this example but I always receive a "TypeError: Object [object Object] has no method echo".

Could you share your project or html page?

chintan khetiya said...


Hello,
Nice post, but i am stuck at one instance,
Is there any limitation of phonegap version to access your code.because i am using 2.9.0 and when i run my app logcat says :: VM Aborting Error.

How to solve this issue. I think your code is easy to communicate with phonegap.

Is there any permission to set in config.xml ?

Thanks please let me know

pouyelayese said...

thanks!