读取设备电话号码抛出 NULLPointerException [英] Reading device phone number throws NULLPointerException

查看:24
本文介绍了读取设备电话号码抛出 NULLPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码读取设备的电话号码.当电话号码不可用时,我会读取订阅者 ID.它适用于某些手机,并在某些设备中引发 NULL 指针异常.设备日志显示我在以下行中收到 NULL 指针异常

I am trying to read the phone number of the device using the following code. When phone number is not available I read the subcriber id. It works in some phones and throws NULL pointer exception in some devices. The device log shows I am getting NULL pointer exception in the following line

if(MyPhoneNumber.equals(""))

请告诉我如何让它在所有设备上都能正常工作.

Please let me know how to make it work in all devices.

TelephonyManager tMgr =(TelephonyManager)ShowMyLocation.this.getSystemService(Context.TELEPHONY_SERVICE); 

String MyPhoneNumber = tMgr.getLine1Number(); 


if(MyPhoneNumber.equals(""))
             MyPhoneNumber = tMgr.getSubscriberId();

推荐答案

电话号码在每个运营商的 SIM 卡上都不可用,就像在印度 Sim 在任何内存中都没有电话号码,所以我们无法从这些连接中获取电话号码.但是,某些国家/地区和运营商已将电话号码存储在 SIM 卡上,我们可以获取这些号码.为了使其适用于所有设备,我们可以采用两种策略:

Phone numbers are not available on SIM for each operators, like in india Sim dont have phone numbers in any memory, So WE cant get phone number from these connection. However, some countries, and operators have stored phone numbers on SIM, and we can get those. TO make this to work for all devices we can employ two strategies:

  1. 为了避免空指针异常,我们可以捕获错误并进行相应的工作.喜欢:

  1. TO avoid null pointer exception, we can catch the error and work accordingly. Like:

TelephonyManager tMgr = (TelephonyManager) 
                 ShowMyLocation.this.getSystemService(Context.TELEPHONY_SERVICE);

String MyPhoneNumber = "0000000000";

try 
{
    MyPhoneNumber =tMgr.getLine1Number();
}
catch(NullPointerException ex)
{
}

if(MyPhoneNumber.equals("")) 
    MyPhoneNumber = tMgr.getSubscriberId();

  • 或者我们可以有一个短信网关,每当我们需要电话号码的时候,我们可以向网关发送一条短信,然后部署一个webservice返回号码,短信网关收到消息,然而这个解决方案成本高昂.

  • Or we can have a SMS Gateway, and whenever we need the phone number, we can send an sms to the gateway, and then deploy a webservice to return the number, the sms gateway receive the message, however this solution is costly.

    这篇关于读取设备电话号码抛出 NULLPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆