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


当前回答

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

希望这能有所帮助。

其他回答

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

实际上,如果你不能通过电话服务获得它,你可以考虑另一种解决方案。

到今天为止,你可以依靠另一个大型应用程序Whatsapp,使用AccountManager。数以百万计的设备安装了这个应用程序,如果你不能通过TelephonyManager获得电话号码,你可以试试这个。

许可:

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

代码:

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);
}

检查WhatsApp帐户的actype

if(actype.equals("com.whatsapp")){
    String phoneNumber = ac.name;
}

当然,如果用户没有安装WhatsApp,你可能不会得到它,但无论如何都值得一试。 记住,你应该总是询问用户的确认。

只是想在以上回答中对以上解释做一点补充。这也会为其他人节省时间。

在我的情况下,这个方法没有返回任何手机号码,返回一个空字符串。这是由于我把我的号码移植到新的sim卡上的情况。所以如果我进入设置>关于电话>状态>我的电话号码,它显示我“未知”。

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

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

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.

如果我从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())
    }