How can I programmatically get the phone number of the device that is running my android app?
There is actually an alternative solution you might want to consider, if you can't get it through telephony service.
As of today, you can rely on another big application Whatsapp, using AccountManager
. Millions of devices have this application installed and if you can't get the phone number via TelephonyManager
, you may give this a shot.
Permission:
Code:
AccountManager am = AccountManager.get(this);
Account[] accounts = am.getAccounts();
for (Account ac : accounts) {
String acname = ac.name;
String actype = ac.type;
// Take your time to look at all available accounts
System.out.println("Accounts : " + acname + ", " + actype);
}
Check actype
for WhatsApp account
if(actype.equals("com.whatsapp")){
String phoneNumber = ac.name;
}
Of course you may not get it if user did not install WhatsApp, but its worth to try anyway. And remember you should always ask user for confirmation.