How to get phone number of a device programmatically [duplicate]

China☆狼群 提交于 2019-12-28 02:51:09

问题


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?


回答1:


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!



来源:https://stackoverflow.com/questions/23675868/how-to-get-phone-number-of-a-device-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!