Java 如何在 Android 中以编程方式获取自己的电话号码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21739656/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:26:04  来源:igfitidea点击:

How can I get my own phone number programmatically in Android?

javaandroidtelephonymanager

提问by Burro

I tried the following code to get my own number and get a NULL string. What is the problem?

我尝试了以下代码来获取我自己的号码并获取一个 NULL 字符串。问题是什么?

TelephonyManager mTelephonyMgr;     
 mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);     
 String phoneNumber = mTelephonyMgr.getLine1Number();

Permission

允许

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

回答by Tim

Add this to your manifest

将此添加到您的清单中

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

You need the user's permission to retrieve this data

您需要用户的许可才能检索此数据

If it still returns null, that means the data is not available, and you cant use it.

如果它仍然返回null,则表示数据不可用,您不能使用它。

See Get my phone number in android

请参阅在 android 中获取我的电话号码

回答by Jorgesys

Use TelephonyManager.getLine1Number()

使用 电话管理器。getLine1Number()

But you need to have stored the phone number on the SIM card, and there′s no other way to get your "own number".

但是您需要将电话号码存储在 SIM 卡上,没有其他方法可以获取您的“自己的号码”。

Example:

例子:

TelephonyManager tm = (TelephonyManager)this.getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE); 
String myPhoneNumber =  tm.getLine1Number();

and you need this permission into your Manifest.xml

你需要这个权限到你的 Manifest.xml

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

See this Question: TelephonyManager.getLine1Number() failing?as describe, you need to evaluate:

请参阅此问题: TelephonyManager.getLine1Number() 失败?如描述,您需要评估:

if("SIM card present" && "phone number is stored") {
  "get the phone number with TelephonyManager.getLine1Number"
}