android - 以编程方式在 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"/>
请你帮助我好吗。
谢谢。
解决方案
一些电话公司不允许从 sim 卡中获取号码,因为我在过去的项目中遇到了同样的问题。
(在过去的项目中,我想在 simcard 号码上发送 OTP,用户不能输入他的号码。这是出于安全目的。)所以一些电话给你正确的输出,仍然给你输出为 NULL
推荐阅读
- laravel - 通过 CLI 启动 Horizon 后,有没有办法调用自定义命令?
- wso2 - WSO2IS - 为现有部署升级 PasswordDigest 属性
- google-sheets - 如何在同一单元格中将日期变量的格式更改为“季度”?
- java - 我将如何为这样的算法建立递归关系?
- python - 如何创建一个新列,该列是特定范围内满足多个条件的列数的总和
- android - 空对象引用上的错误“java.lang.Class java.lang.Object.getClass()”
- javascript - jQuery在页面卸载时打破每个循环
- ruby-on-rails - 为什么 Rails 中的 SSE 挂在连接上?
- javascript - TypeScript 和 Redux:为什么我需要添加 ` | undefined` 到我的 Reducer 状态类型?
- npm - npm install 在 node_modules 的父文件夹中下载额外的依赖项