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


当前回答

对于android版本>= LOLLIPOP_MR1:

增加权限:

叫它:

 val subscriptionManager =
        getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE) as SubscriptionManager
    
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
        
val list = subscriptionManager.activeSubscriptionInfoList
        for (info in list) {
            Log.d(TAG, "number " + info.number)
            Log.d(TAG, "network name : " + info.carrierName)
            Log.d(TAG, "country iso " + info.countryIso)
        }
    }

其他回答

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.

正如我之前回答的那样

使用以下代码:

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

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

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

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

另外,试着在电话->设置->关于->电话身份,如果你能在那里看到号码,从上面的代码获得电话号码的概率更高。如果您不能在设置中查看电话号码,那么您将无法通过此代码获得!

建议解决方案:

获取用户的电话号码作为用户的手动输入。 通过短信将代码发送到用户的手机号码。 请用户输入确认电话号码的代码。 保存在sharedpreference中。

在应用首次发布时一次性执行上述4个步骤。稍后,当需要电话号码时,使用共享首选项中可用的值。

如果我从voiceMailNumer得到数字,那么它工作得很好-

val telephonyManager = getSystemService(TELEPHONY_SERVICE) as TelephonyManager
    if (ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED
    ) {
        Log.d("number", telephonyManager.voiceMailNumber.toString())
    }

虽然你可以有多个语音信箱帐号,但当你用自己的号码打电话时,运营商会把你转到语音信箱。因此,telephonymanager。getvoicemailnumber()或telephonymanager。getcompletevoicemailnumber(),这取决于你需要的风格。

希望这能有所帮助。

对于android版本>= LOLLIPOP_MR1:

增加权限:

叫它:

 val subscriptionManager =
        getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE) as SubscriptionManager
    
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
        
val list = subscriptionManager.activeSubscriptionInfoList
        for (info in list) {
            Log.d(TAG, "number " + info.number)
            Log.d(TAG, "network name : " + info.carrierName)
            Log.d(TAG, "country iso " + info.countryIso)
        }
    }