我在尝试向无效号码发送短信时遇到NullPointerException(无效我的意思是包含字母字符等的电话号码,而不是服务中断号码)
我使用的代码来自本教程: http://mobiforge.com/developing/story/sms-messaging-android
//---sends an SMS message to another device---
private void sendSMS(String phoneNumber, String message)
{
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
new Intent(DELIVERED), 0);
//---when the SMS has been sent---
registerReceiver(new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
//---when the SMS has been delivered---
registerReceiver(new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS delivered",
Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getBaseContext(), "SMS not delivered",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(DELIVERED));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
}
当用户碰巧输入无效的电话号码时,应用程序崩溃并不是最好的。所以我的问题是处理这个问题的好方法是什么?
我可以从这段代码中捕获NullPointerExceptions然后引发错误toast,但似乎NullPointerException也会引发其他错误,例如如果消息太长而且应该是多部分的。
另一种愚蠢的方法是限制EditText只接受数字和'+'字符。
我对这些解决方案中的任何一个都不满意 - 在我看来,理想情况下,sendTextMessage方法应该引发更多信息性异常或为此广播错误代码?
答案 0 :(得分:0)
将edittext的输入类型设置为电话号码效果很好。通过“电话号码”输入小部件输入的任何数字组合似乎都不会引发异常(例如“#*,()123”)
在XML中:
android:inputType="phone"
感谢awadm指出我正确的方向