Android 如何以编程方式获取设备的电话号码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23675868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get phone number of a device programmatically
提问by Android Priya
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?
但每次我得到一个空的电话号码。我什至试图从 WhatsApp 获取电话号码,但它返回的是“WhatsApp”而不是电话号码。有没有其他方法可以解决这个问题?
回答by Nishanthi Grashia
Use below code :
使用以下代码:
TelephonyManager tMgr = (TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();
In AndroidManifest.xml, give the following permission:
在 AndroidManifest.xml 中,赋予以下权限:
<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.
但请记住,此代码并不总是有效,因为手机号码取决于 SIM 卡和网络运营商/手机运营商。
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!
另外,尝试检查Phone--> Settings --> About --> Phone Identity,如果您能够在那里查看号码,则从上面的代码中获取电话号码的可能性更高。如果您在设置中无法查看电话号码,那么您将无法通过此代码获取!