如何以编程方式获取设备的电话号码 [英] How to get phone number of a device programmatically

查看:207
本文介绍了如何以编程方式获取设备的电话号码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下方法获取电话号码:

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;
}

但是每次我得到一个空电话号码时.我什至尝试从WhatsApp获取电话号码,但它返回的是"WhatsApp"而不是电话号码. 还有其他方法可以解决这个问题吗?

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?

推荐答案

使用以下代码:

TelephonyManager tMgr = (TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();

在AndroidManifest.xml中,授予以下权限:

In AndroidManifest.xml, give the following permission:

 <uses-permission android:name="android.permission.READ_PHONE_STATE"/> 

但是请记住,由于手机号码取决于SIM卡和网络运营商/手机运营商,因此此代码并不总是有效.

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!

这篇关于如何以编程方式获取设备的电话号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆