首页 > 解决方案 > 以编程方式在 Android 中获取电话号码

问题描述

在我的 Android 应用程序中,我需要显示设备中可用的 SIM 卡的电话号码。

我尝试使用以下代码

 private String getPhone() {
    TelephonyManager phoneMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    if (ActivityCompat.checkSelfPermission(activity, wantPermission) != PackageManager.PERMISSION_GRANTED) {
        return "";
    }
    return phoneMgr.getLine1Number();
}

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
List<SubscriptionInfo> subscription = SubscriptionManager.from(getApplicationContext()).getActiveSubscriptionInfoList();
for (int i = 0; i < subscription.size(); i++) {
    SubscriptionInfo info = subscription.get(i);
    Log.d(TAG, "number " + info.getNumber());
    Log.d(TAG, "network name : " + info.getCarrierName());
    Log.d(TAG, "country iso " + info.getCountryIso());
}

}

但两者都只返回 null 或空字符串。

我也添加了清单权限。

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

请你帮助我好吗。

谢谢。

标签: android

解决方案


一些电话公司不允许从 sim 卡中获取号码,因为我在过去的项目中遇到了同样的问题。

(在过去的项目中,我想在 simcard 号码上发送 OTP,用户不能输入他的号码。这是出于安全目的。)所以一些电话给你正确的输出,仍然给你输出为 NULL


推荐阅读