Thursday, December 6, 2012

How to Get the Device's Phone Number Using PhoneGap Android

I was a bit surprised when three people asked me how to do this in one day. I figured if there was enough interest in it then maybe it deserved a post of it's own. Basically you want to know the primary phone number of the device your app is running on. In order to do that in PhoneGap you will need to write a plugin to access the TelephonyManager service on Android.

As always the code for this plugin is is GitHub at my TelephoneNumberPlugin repo. If you'd rather have a more detailed walk through please read on.
First up let's code our JavaScript interface which we will use to get the telephone number. We'll setup a new interface at "cordova/plugin/telephonenumber" to avoid name collisions. Then the rest is fairly boiler plate code where we declare and error object that we won't even use and finally provide a get method. When you call the get method you should provide a success callback. The success callback will be invoked with a string that will contain the devices phone number. If something goes wrong the failure callback will be invoked.

I've extracted the execute method from TelephoneNumber.java which extends from the new CordovaPlugin interface. The method is fairly self explanatory. If the device has a phone number it will be returned. If not the error call back is invoked with the NO_TELEPHONE_NUMBER error code. If you try to call anything other than "get" on this class you'll get a INVALID_ACTION error.

In order to use this plugin you'll need to include the telephonenumber.js in your HTML as a script tag:

and add a line to res/xml/config.xml to tell the JavaScript side where to find your Java class:

and if you don't already have READ_PHONE_STATE as a permission in your AndroidManifest.xml you will need to add it as well.

Now you should be able to get your devices phone number. Here is some sample code that writes the phone number out to the console:

49 comments:

BorG said...

Hi Simon,

great post, thanks!

BTW, can such a plugin be written in iOS/WP7+/BB?

Simon MacDonald said...

@BorG

Yes, of course. Reuse the JS but each OS will need its own native implementation.

Raymond Camden said...

Any particular reason why you would limit this to just the telephone number and not make a more generic plugin? Looking at the API (http://developer.android.com/reference/android/telephony/TelephonyManager.html), there appears to be other things in there that might be of use as well. (Although certainly none as much as the main telephone #.)

Simon MacDonald said...

@Raymond Camden

No reason other than that was the question that I was trying to answer for the three or so folks who contacted me. It would be pretty easy to add more capabilities to the plugin and since it is up on Github I welcome pull requests from anyone that has done so.

Vasu Nanguluri said...

Hey Simon, I have tried your code but no luck, Its working on Android 4.0.4. Not working on below version's plz help me form this issue.

Simon MacDonald said...

@Vasu Nanguluri

Define, no luck.

jagadesh said...

Hi Simon,

It was very great to have the article, but i have trying to send the sms in background, but i was not much sucessfull, could you help me in this issue.

could you send me any sample if you have, i have tried the sample in the github i was getting the exception "Uncaught TypeError : Cannot read property 'sms' of undefined".

Simon MacDonald said...

@jagadesh

What code on github are you using? It sounds like the plugin you are using is not updated for Cordova 2.0.0 or greater.

sangeeth_LVS said...

HI simon,

i need to know is there any database in android storing the total sms count .

if i use content://sms/ it is returning only the available sms count in the mobile but i want overall sms count sent form the mobile from the begining ..

thanks in advance
Sangeeth

jagadesh said...

Dear Simon,

Could you help me in integrating the Facebook, linked in phonegap, I have tried a lot but had no luck.

Thanks in advance

Simon MacDonald said...

@sangeeth_LVS

To the best of my knowledge content://sms will only give you the total number of SMS currently on the device. If you want to get an idea of every SMS ever received by the device you'll need to create an app that keeps track of it.

Simon MacDonald said...

@jagadesh

I hate Facebook with a passion that I usually reserve for opponent hockey teams (think of that cricket team you love to hate). So sorry, no I've never tried to integrate with Facebook.

Geoffrey Giordano said...

This is super, thank you.
One question (I'm still new w/phonegap), I'm running cordova-2.3.0, when I add this plugin, I get the error:

02-12 11:14:37.786: E/Web Console(380): module cordova/plugins/telephonenumber not found at undefined:0

in my log. However, the plugin seems to be working? I must have missed something, but I'm at a loss as to what.

Simon MacDonald said...

@Geoffrey Giordano

That was a mis-spelling on my part. I've fixed it on github. Go grab the lastest JS file for the fix.

robds said...

Hi Simon,

Thanks for this, but having some difficulty getting this working. I've followed the instructions exactly (or so I believe!) and I'm getting this error:

E/Web Console(12504): Uncaught module cordova/plugin/telephonenumber not found at file:///android_asset/www/cordova-2.3.0.js:48

Any suggestions?

Thanks

robds said...

Oops, solved it. Like an idiot I put telephonenumber.js in the wrong place. :) Thanks a lot for this plugin!

Navjot Singh said...

Hi Simon,

I read your blog. It was very great to have the article. i am new to phonegap and using cordova2.4.0 version. i have one query related to cordova.define(path). what is path here means you are asking (cordova/plugin/ipaddress)

Simon MacDonald said...

@Navjot Singh

I saw your email on this question. You did not include the script tag for telephonenumber.js.

Navjot Singh said...

@simon MacDonald many many thanks to you

Navjot Singh said...

Hi simon

i have using cordova2.4.0 and when i run a demo project for testing plugin is working or not getting an error "Falling back on PROMPT mode since _cordovaNative is missing."

when app is run after that i click on app than i got error "Invalid action"

i am using this code with my new cordova 2.4.0 version.

download.macromedia.com/pub/developer/phonegap/myfirstphonegapplugin_a.zip

can you please help me.


Thanks & regards
Navjot singh
Skype : navjotsinghmca

Simon MacDonald said...

@Navjot Singh

Well when I import that code into Eclipse it runs just fine. However it is using Cordova 1.6.1. If you are running against 2.4.0 with the same code you will run into an issue where some of the API's are deprecated but it should still run. The JS will need to change a bit.

Try...

var exec = cordova.require("cordova/exec");
var HelloPlugin = {

callNativeFunction: function (success, fail, resultType) {
return exec(success, fail, "com.tricedesigns.HelloPlugin", "nativeAction", [resultType]);
}
};

xakim said...

@Simon

Could you explain what you meant earlier when you said

"Yes, of course. Reuse the JS but each OS will need its own native implementation." ?

I don't understand how to apply this to iOS.

Simon MacDonald said...

@xakim

Take the same JS file then write the native plugin for iOS.

http://docs.phonegap.com/en/2.5.0/guide_plugin-development_ios_index.md.html#Developing%20a%20Plugin%20on%20iOS

Prashanth Rao said...

Hi Simon,
I followed all the instruction above and developed app which gets quite a few phone/sim information.

It works on Samsung Galaxy Nexus and does not work on any HTC phone. I googled and found some issue related to hydration. Can you please let me know how I can fix it for HTC ?

I am using Eclipse to build and deploy app on my local box, I have not uploaded my app anywhere.

Any help really appeciated.

Cheers,
Prashanth

Simon MacDonald said...

@Prashanth Rao

Sorry some vendors don't publish the phone number to the SIM card. You'll have to ask the user for it.

Prashanth Rao said...

@Simon
Thanks for the info. I will try and see how i can get around few tricky bits.

Cheers,
Prashanth

Mohan Kuldeep Ponnada said...

Hi Simon

Great work, thanks much for the plugin.

I am using cordova 2.7 and trying to console log the phone number, I have tried many sim cards but it returns blank.

Is there a different way to write the JS file for this version of cordova? or will the existing JS work?

Thanks much

Mohan

Simon MacDonald said...

@Mohan Kuldeep Ponnada

Sorry not every vendor puts the number on the SIM card.

DesignerOfArt said...

Can this be used on an iPhone? Please say yes? If it can't, how can it then be used on an iPhone?

Simon MacDonald said...

@DesignerOfArt

No, I only wrote the Android version of this plugin. It is possible in iOS though, someone just has to write it.

sree kanth said...

Hi Simon,

In my application i have to get both the mobile numbers from dual sim phone? Here in your application we can able to get only one mobile number.

Is there any way to get both the numbers? Please help it is very important for me?

Simon MacDonald said...

@sree kanth

There is no Android API to support dual sim's. Most phones that have this capability are extended by the manufacturers and they are not making the API available.

Check out this app:

http://www.qianqin.de/multisim/

You may want to contact the developer to see if he can help you.

Unknown said...

Hello Simon,

Thanks for your post ! I have remarked that the code you propose doesn't compile on Cordova 3.0. By looking at some modifications made to the PushPlugin phonegap plugin, I just changed the TelephoneNumber.java from:
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.apache.cordova.api.PluginResult;
To:
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;

It compiles and launches on the device, yet I have no SIM yet to confirm that you really can retrieve the phone number. If someone can test it, I would be really happy to get feedback.

Simon MacDonald said...

@Unknown

Yeah, that looks correct. I haven't had the chance to go through all my plugins to update them to 3.0.0 but I hope to get to it soon.

Rahul kumar said...

Hi Simon,
I want to access sms messages from my android device into listview. After accessing messages if we get new message automatically the list should be refresh. And if we delete any message from the list the message have to be deleted from the list and device.

Please help me it is very useful for me.
Thanks in Advance.
Here is the sample code written by me

List smsList = new ArrayList();

Uri uri = Uri.parse("content://sms/");
Cursor c= getContentResolver().query(uri, null, null ,null,null);
startManagingCursor(c);

// Read the sms data and store it in the list
if(c.moveToFirst()) {
for(int i=0; i < c.getCount(); i++) {
SMSData sms = new SMSData();
sms.setBody(c.getString(c.getColumnIndexOrThrow("body")).toString());
sms.setNumber(c.getString(c.getColumnIndexOrThrow("address")).toString());
sms.setDate(c.getString(c.getColumnIndexOrThrow("date")).toString());
smsList.add(sms);

c.moveToNext();
}
}
c.close();

// Set smsList in the ListAdapter
setListAdapter(new ListAdapter(this, smsList));

Simon MacDonald said...

@Rahul kumar

Look at this stack overflow answer:

http://stackoverflow.com/questions/2584058/android-querying-the-sms-contentprovider

sandeep parashar said...

hi Simon,
i am trying to use this with phoneGap, i have follow all the steps which u have mention in "https://github.com/macdonst/TelephoneNumberPlugin". then it is shown Jquery error : can't find variable Cordova in teliphonenumber.js.
and can't find the variable require in cordova.js.. please tell me what is the issue

Simon MacDonald said...

@sandeep parashar

Have you loaded the cordova.js file?

Ben Dorsi -Todaro said...

Okay not very good at JQuery yet so bare with me. What am I doing wrong in this http://pastebin.com/QKbsZPhp

Simon MacDonald said...

@Ben Dorsi -Todaro

Nowhere in your sample do I see you loading the PhoneGap/Cordova JavaScript file which is necessary for my telephone number plugin to work.

Vasu Nanguluri said...

HI Simon,

Thanks for great post, I used this code in my sample app its working great, but for some mobile its returning null value in the place of mobile number, can you please help me on this issue its great full for me

Simon MacDonald said...

@Vasu Nanguluri

Not all mobile phone vendor's put the phone number on the SIM. That is probably what is happening to you. I had the same problem using T-Mobile in the Netherlands.

Flanagan Khumbula said...

Hi Simon...i am getting the error "Class not found" what could be the problem?

Simon MacDonald said...

@Flanagan Khumbula

That generally means you forgot to add the plugin line to plugins.xml or config.xml depending on your version of PhoneGap.

muneeb khan said...

Hi there, i have added the plugin in my project in the src folder then edited the config.xml and the index.html and uploaded it to build.phonegap.com but it says this prooject has no plugins please help

Simon MacDonald said...

@muneeb khan

Sorry I don't use the build.phonegap.com site for my own apps. I think you'd have to follow their directions on how to add a custom plugin like this one.

SHYAAM said...

Hello Simon,


Great post,

I have not implemented this yet,
But I am very happy to see it.

This is exactly what I was looking for :)

Ganesh Sharma said...

hii simon plz help me i am using cordova 2.1.0 . when i am implementing this i have get "errr= class not found" . i have added plugin to my config.xml.


Simon MacDonald said...

@Ganesh Sharma

If I remember correctly the "cordova" object was not in 2.1 so you may need to update your version of PhoneGap in order to use this plugin.