以编程方式获取Android手机的电话号码

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

Programmatically obtain the phone number of the Android phone

androidphone-numbertelephonymanager

提问by jkap

How can I programmatically get the phone number of the device that is running my android app?

如何以编程方式获取运行我的 android 应用程序的设备的电话号码?

回答by Alex Volovoy

Code:

代码:

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

Required Permission:

所需权限:

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

Caveats:

注意事项:

According to the highly upvoted comments, there are a few caveats to be aware of. This can return nullor ""or even "???????", and it can return a stale phone number that is no longer valid. If you want something that uniquely identifies the device, you should use getDeviceId()instead.

根据高度赞成的评论,有一些注意事项需要注意。这可以返回nullor""甚至"???????",并且它可以返回不再有效的陈旧电话号码。如果你想要唯一标识设备的东西,你应该使用getDeviceId()

回答by Johan

There is no guaranteed solution to this problem because the phone number is not physically stored on all SIM-cards, or broadcasted from the network to the phone. This is especially true in some countries which requires physical address verification, with number assignment only happening afterwards. Phone number assignment happens on the network - and can be changed without changing the SIM card or device (e.g. this is how porting is supported).

此问题没有保证的解决方案,因为电话号码并未物理存储在所有 SIM 卡上,或从网络广播到电话。在一些需要物理地址验证的国家尤其如此,号码分配仅在之后进行。电话号码分配发生在网络上 - 无需更改 SIM 卡或设备即可更改(例如,这是支持移植的方式)。

I know it is pain, but most likely the best solution is just to ask the user to enter his/her phone number once and store it.

我知道这很痛苦,但很可能最好的解决方案是让用户输入一次他/她的电话号码并存储它。

回答by Chor Wai Chun

Update: This answer is no longer available as Whatsapp had stopped exposing the phone number as account name, kindly disregard this answer.

更新:此答案不再可用,因为 Whatsapp 已停止将电话号码公开为帐户名,请忽略此答案。

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.

截至今天,您可以依赖另一个大型应用程序 Whatsapp,使用AccountManager. 数以百万计的设备安装了此应用程序,如果您无法通过 获取电话号码TelephonyManager,您可以试一试。

Permission:

允许:

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

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 actypefor WhatsApp account

检查actypeWhatsApp 帐户

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.

当然,如果用户没有安装 WhatsApp,您可能无法获得它,但无论如何都值得一试。请记住,您应该始终要求用户进行确认。

回答by Nishanthi Grashia

As posted in my earlier answer

正如我之前的回答中所发布的

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,如果您能够在那里查看号码,则从上面的代码中获取电话号码的可能性更高。如果您在设置中无法查看电话号码,那么您将无法通过此代码获取!

Suggested Workaround:

建议的解决方法:

  1. Get the user's phone number as manual input from the user.
  2. Send a code to the user's mobile number via SMS.
  3. Ask user to enter the code to confirm the phone number.
  4. Save the number in sharedpreference.
  1. 从用户手动输入获取用户的电话号码。
  2. 通过短信向用户的手机号码发送代码。
  3. 要求用户输入代码以确认电话号码。
  4. 将号码保存在共享首选项中。

Do the above 4 steps as one time activity during the app's first launch. Later on, whenever phone number is required, use the value available in shared preference.

在应用程序首次启动期间,将上述 4 个步骤作为一次性活动执行。稍后,每当需要电话号码时,请使用共享首选项中的可用值。

回答by Dmide

So that's how you request a phone number through the Play Services API without the permission and hacks. Sourceand Full example.

这就是您在未经许可和黑客攻击的情况下通过 Play Services API 请求电话号码的方式。源代码完整示例

In your build.gradle (version 10.2.x and higher required):

在您的 build.gradle 中(需要 10.2.x 及更高版本):

compile "com.google.android.gms:play-services-auth:$gms_version"

In your activity (the code is simplified):

在您的活动中(代码已简化):

@Override
protected void onCreate(Bundle savedInstanceState) {
    // ...
    googleApiClient = new GoogleApiClient.Builder(this)
            .addApi(Auth.CREDENTIALS_API)
            .build();
    requestPhoneNumber(result -> {
        phoneET.setText(result);
    });
}

public void requestPhoneNumber(SimpleCallback<String> callback) {
    phoneNumberCallback = callback;
    HintRequest hintRequest = new HintRequest.Builder()
            .setPhoneNumberIdentifierSupported(true)
            .build();

    PendingIntent intent = Auth.CredentialsApi.getHintPickerIntent(googleApiClient, hintRequest);
    try {
        startIntentSenderForResult(intent.getIntentSender(), PHONE_NUMBER_RC, null, 0, 0, 0);
    } catch (IntentSender.SendIntentException e) {
        Logs.e(TAG, "Could not start hint picker Intent", e);
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == PHONE_NUMBER_RC) {
        if (resultCode == RESULT_OK) {
            Credential cred = data.getParcelableExtra(Credential.EXTRA_KEY);
            if (phoneNumberCallback != null){
                phoneNumberCallback.onSuccess(cred.getId());
            }
        }
        phoneNumberCallback = null;
    }
}

This will generate a dialog like this:

这将生成一个对话框,如下所示:

enter image description here

在此处输入图片说明

回答by Emil Hajric

private String getMyPhoneNumber(){
    TelephonyManager mTelephonyMgr;
    mTelephonyMgr = (TelephonyManager)
        getSystemService(Context.TELEPHONY_SERVICE); 
    return mTelephonyMgr.getLine1Number();
}

private String getMy10DigitPhoneNumber(){
    String s = getMyPhoneNumber();
    return s != null && s.length() > 2 ? s.substring(2) : null;
}

Code taken from http://www.androidsnippets.com/get-my-phone-number

代码取自http://www.androidsnippets.com/get-my-phone-number

回答by Wirling

There is a new Android api that allows the user to select their phonenumber without the need for a permission. Take a look at: https://android-developers.googleblog.com/2017/10/effective-phone-number-verification.html

有一个新的 Android api,允许用户在不需要许可的情况下选择他们的电话号码。看一看:https: //android-developers.googleblog.com/2017/10/effective-phone-number-verification.html

// Construct a request for phone numbers and show the picker
private void requestHint() {
    HintRequest hintRequest = new HintRequest.Builder()
       .setPhoneNumberIdentifierSupported(true)
       .build();

    PendingIntent intent = Auth.CredentialsApi.getHintPickerIntent(
        apiClient, hintRequest);
    startIntentSenderForResult(intent.getIntentSender(),
        RESOLVE_HINT, null, 0, 0, 0);
} 

回答by activesince93

Sometimes, below code returns nullor blank string.

有时,下面的代码返回null或空白字符串。

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

With below permission

经以下许可

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

There is another way you will be able to get your phone number, I haven't tested this on multiple devices but above code is not working every time.

还有另一种方法可以获得您的电话号码,我没有在多台设备上测试过这个,但上面的代码并不是每次都有效。

Try below code:

试试下面的代码:

String main_data[] = {"data1", "is_primary", "data3", "data2", "data1", "is_primary", "photo_uri", "mimetype"};
Object object = getContentResolver().query(Uri.withAppendedPath(android.provider.ContactsContract.Profile.CONTENT_URI, "data"),
        main_data, "mimetype=?",
        new String[]{"vnd.android.cursor.item/phone_v2"},
        "is_primary DESC");
if (object != null) {
    do {
        if (!((Cursor) (object)).moveToNext())
            break;
        // This is the phoneNumber
        String s1 = ((Cursor) (object)).getString(4);
    } while (true);
    ((Cursor) (object)).close();
}

You will need to add these two permissions.

您将需要添加这两个权限。

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

Hope this helps, Thanks!

希望这有帮助,谢谢!

回答by user_CC

Just want to add a bit here to above explanations in the above answers. Which will save time for others as well.

只是想在上面的答案中对上面的解释添加一点。这也将为其他人节省时间。

In my case this method didn't returned any mobile number, an empty string was returned. It was due to the case that I had ported my number on the new sim. So if I go into the Settings>About Phone>Status>My Phone Number it shows me "Unknown".

就我而言,此方法没有返回任何手机号码,而是返回了一个空字符串。这是因为我在新的 SIM 卡上移植了我的号码。因此,如果我进入“设置”>“关于电话”>“状态”>“我的电话号码”,它会显示“未知”。

回答by E P Lewis

This is a more simplified answer:

这是一个更简单的答案:

public String getMyPhoneNumber()
{
    return ((TelephonyManager) getSystemService(TELEPHONY_SERVICE))
            .getLine1Number();
}