Android Phone nr access可在手机中使用,但在平板电脑上即使使用try/catch也会崩溃
我有一个Android手机应用程序,可以访问手机号码获取注册信息,如下所示:Android Phone nr access可在手机中使用,但在平板电脑上即使使用try/catch也会崩溃,android,Android,我有一个Android手机应用程序,可以访问手机号码获取注册信息,如下所示: String thisPhoneNumber = "0"; try { TelephonyManager tMgr=(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE); thisPhoneNumber = tMgr.getLine1Number(); } catch (Exception e)
String thisPhoneNumber = "0";
try {
TelephonyManager tMgr=(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
thisPhoneNumber = tMgr.getLine1Number(); }
catch (Exception e) { }
它在电话上很好用。一位朋友在平板电脑上试用了它(最近的一款),应用程序崩溃了。如果我注释掉try/catch的4行代码,它工作得很好,所以看起来崩溃一定是在getSystemService调用中发生的
在搜索stackoverflow时,听起来代码应该在任何一个平台上运行,但这不是我看到的
try/catch不应该防止崩溃并允许处理异常吗
是否有其他方法允许getSystemService在平板电脑上执行而不会崩溃?或者我不必在平板电脑上进行调用吗?使用if语句检查这2-3行中的变量是否为null,如果是,则停止执行代码 试一试 { TelephonyManager tMgr=(TelephonyManager)getSystemService(Context.TELEPHONY_服务); 如果(tMgr!=null) thisPhoneNumber=tMgr.getLine1Number();} cath(例外情况o) {} 或者,您可以尝试查找该设备是平板电脑还是手机(手机还是非手机设备) 然后在if代码中执行两个不同的语句 如果(电话){代码} 或者,您可以使用函数find phone number创建抽象类 有人这样想吗
if(device is phone)
{
apstractClass=new phoneImplementation();
} else
{
apstractClass= new nonPhoneImplementation();if (((TelephonyManager)getContext().getSystemService(Context.TELEPHONY_SERVICE)).getLine1Number()
== null)
{
//没有电话
}在此处输入代码
}
thisPhoneNumber=apstarctClass.getPhoneNumber()
其中phoneImplementation().getPhoneNumber()将包含您的代码,来自问题和非phoneImplementation()的代码。getPhoneNumber()将返回0
如果设备具有电话功能,您可以使用此选项进行检查
if (((TelephonyManager)getContext().getSystemService(Context.TELEPHONY_SERVICE)).getLine1Number()
== null)
{
// no phone
}
我的意见是,这将解决您的问题:
String thisPhoneNumber = "0";
try
{
if (((TelephonyManager)getContext().getSystemService(Context.TELEPHONY_SERVICE)).getLine1Number()
!= null)
{
thisPhoneNumber = tMgr.getLine1Number();
} }
catch(Exception o)
{}