I am trying to get phone no using following method:
private String getMyPhoneNumber() {
TelephonyManager mTelephonyMgr;
mTelephonyMgr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
//String imsi = mTelephonyMgr.getSubscriberId();
String phnNo = mTelephonyMgr.getLine1Number();
if (phnNo == null) {
phnNo = getNoFromWatsApp();
}
return phnNo;
}
private String getNoFromWatsApp(){
AccountManager am = AccountManager.get(this);
Account[] accounts = am.getAccounts();
String phoneNumber = "";
for (Account ac : accounts) {
String acname = ac.name;
String actype = ac.type;
// Take your time to look at all available accounts
if(actype.equals("com.whatsapp")) {
phoneNumber = ac.name;
}
}
return phoneNumber;
}
But every time I get an empty phone number. I even tried to get phone number from WhatsApp but it's returning "WhatsApp" instead of phone number. Is there any other way to solve this problem?
Use below code :
TelephonyManager tMgr = (TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();
In AndroidManifest.xml, give the following permission:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
But remember, this code does not always work, since Cell phone number is dependent on the SIM Card and the Network operator / Cell phone carrier.
Also, try checking in Phone--> Settings --> About --> Phone Identity, If you are able to view the Number there, the probability of getting the phone number from above code is higher. If you are not able to view the phone number in the settings, then you won't be able to get via this code!