处理短信应用,该应用在收到新消息后崩溃。问题似乎在于广播接收器的传入短信,但我无法弄清楚原因。
广播接收器:
public class SMSBroadcastReceiver extends BroadcastReceiver {
public static final String SMS_BUNDLE = "pdu";
public void onReceive(Context context, Intent intent) {
Bundle intentExtras = intent.getExtras();
if (intentExtras != null) {
Object[] sms = (Object[]) intentExtras.get(SMS_BUNDLE);
String smsMessageStr = "";
for (int i = 0; i < sms.length; ++i) { //Line 24
String format = intentExtras.getString("format");
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i], format);
String smsBody = smsMessage.getMessageBody().toString();
String address = smsMessage.getOriginatingAddress();
smsMessageStr += "SMS From: " + address + "\n";
smsMessageStr += smsBody + "\n";
}
Toast.makeText(context, "Message Received!", Toast.LENGTH_SHORT).show();
if (MainActivity.active) {
MainActivity inst = MainActivity.instance();
inst.updateInbox(smsMessageStr);
} else {
Intent i = new Intent(context, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
}
}
我在第24行标记了调用异常的地方。
错误:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.haltaar.texting, PID: 15909
java.lang.RuntimeException: Unable to start receiver com.example.haltaar.texting.SMSBroadcastReceiver: java.lang.NullPointerException: Attempt to get length of null array
at android.app.ActivityThread.handleReceiver(ActivityThread.java:3194)
at android.app.ActivityThread.-wrap17(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1672)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.NullPointerException: Attempt to get length of null array
at com.example.haltaar.texting.SMSBroadcastReceiver.onReceive(SMSBroadcastReceiver.java:24)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:3187)
at android.app.ActivityThread.-wrap17(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1672)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
任何人都可以帮忙解释一下吗?正确调用AFAIK所有权限,并检查intentExtras是否为null应该在检查时阻止sms对象为空?或者我错过了什么?
答案 0 :(得分:0)
在调用intent.hasExtra(SMS_BUNDLE)
之前检查intent.get(SMS_BUNDLE)
以防止空指针异常