读取设备电话号码会抛出NULLPointerException

use*_*931 1 android nullpointerexception phone-number

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

if(MyPhoneNumber.equals(""))
Run Code Online (Sandbox Code Playgroud)

请让我知道如何使它在所有设备上运行.

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

String MyPhoneNumber = tMgr.getLine1Number(); 


if(MyPhoneNumber.equals(""))
             MyPhoneNumber = tMgr.getSubscriberId();
Run Code Online (Sandbox Code Playgroud)

jee*_*eet 6

每个运营商都没有SIM卡上的电话号码,比如印度的Sim在任何内存中都没有电话号码,所以我们无法通过这些连接获得电话号码.但是,一些国家和运营商已经在SIM卡上存储了电话号码,我们可以获得这些号码.为了使其适用于所有设备,我们可以采用两种策略:

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

    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();
    
    Run Code Online (Sandbox Code Playgroud)
  2. 或者我们可以拥有一个SMS网关,每当我们需要电话号码时,我们都可以向网关发送短信,然后部署网络服务以返回号码,短信网关接收消息,但这种解决方案成本很高.