我如何通过编程方式获得正在运行我的android应用程序的设备的电话号码?


当前回答

这是一个更简单的答案:

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

其他回答

while working on a security app which needed to get the phone number of who so ever my phone might get into their hands, I had to do this; 1. receive Boot completed and then try getting Line1_Number from telephonyManager which returns a string result. 2. compare the String result with my own phone number and if they don't match or string returns null then, 3. secretly send an SMS containing the string result plus a special sign to my office number. 4. if message sending fails, start a service and keep trying after each hour until sent SMS pending intent returns successful. With this steps I could get the number of the person using my lost phone. it doesn't matter if the person is charged.

一点小小的贡献。在我的例子中,代码启动了一个错误异常。我需要把一个注释,为代码运行和修复这个问题。这里我让这段代码。

public static String getLineNumberPhone(Context scenario) {
    TelephonyManager tMgr = (TelephonyManager) scenario.getSystemService(Context.TELEPHONY_SERVICE);
    @SuppressLint("MissingPermission") String mPhoneNumber = tMgr.getLine1Number();
    return mPhoneNumber;
}

首先在Intent中初始化你的符号

private val signInIntent = registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { result ->
        try {
            val phoneNumber = Identity.getSignInClient(requireContext()).getPhoneNumberFromIntent(result.data)
            // Note phone number will be in country code + phone number format           
        } catch (e: Exception) {
        }
    }

要打开谷歌播放意图,并显示与谷歌帐户相关联的电话号码,请使用此

val phoneNumberHintIntentRequest = GetPhoneNumberHintIntentRequest.builder()
            .build()
        Identity.getSignInClient(requireContext())
            .getPhoneNumberHintIntent(phoneNumberHintIntentRequest)
            .addOnSuccessListener { pendingIntent ->
                signInIntent.launch(IntentSenderRequest.Builder(pendingIntent).build())
            }.addOnFailureListener {
                it.printStackTrace()
            }

注意:

如果用户禁用电话号码共享,此操作将失败。如果是这样,用户必须从设置->谷歌->自动填充->电话号码共享 如果您正在使用播放服务不可用的模拟设备,这将不起作用

TelephonyManager不是正确的解决方案,因为在某些情况下,号码没有存储在SIM卡中。我建议您在应用程序第一次打开时使用共享首选项存储用户的电话号码,并且在需要时使用该号码。

这是一个更简单的答案:

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