我试图在Android上阅读短信。一切都很好,除非我试图访问SmsMessage
对象中的某些值时出错:
12-29 17:41:58.762: E/AndroidRuntime(5545): java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.android.internal.telephony.SmsMessageBase.getDisplayOriginatingAddress()' on a null object reference
12-29 17:41:58.762: E/AndroidRuntime(5545): at android.telephony.SmsMessage.getDisplayOriginatingAddress(SmsMessage.java:517)
我在AndroidManifest.xml中注册了Receiver,并扩展了BroadcastReceiver
创建的类SmsReceiver
。
我创建SmsMessage
个对象的方法。
private final SmsMessage[] getMessagesFromIntent(Intent intent) {
Object[] messages = (Object[]) intent.getSerializableExtra("pdus");
byte[][] pduObjs = new byte[messages.length][];
for (int i = 0; i < messages.length; i++) {
pduObjs[i] = (byte[]) messages[i];
}
byte[][] pdus = new byte[pduObjs.length][];
int pduCount = pdus.length;
SmsMessage[] msgs = new SmsMessage[pduCount];
for (int i = 0; i < pduCount; i++) {
pdus[i] = pduObjs[i];
msgs[i] = SmsMessage.createFromPdu(pdus[i]);
}
return msgs;
}
方法onReceive
@Override
public void onReceive(Context context, Intent intent) {
SmsMessage[] messagesArray = getMessagesFromIntent(intent);
for (SmsMessage message : messagesArray) {
String sender = message.getDisplayOriginatingAddress(); //the application fails here
String order = message.getMessageBody().toString();
//...
}
}
我尝试了方法Intents.getMessagesFromIntent(intent)
但没有效果
答案 0 :(得分:3)
我在AndroidManifest.xml中注册了Receiver,并通过扩展BroadcastReceiver创建了类SmsReceiver。
由于您尚未发布AndroidManifest.xml,我假设您正在注册您的接收器
<receiver android:name=". SmsReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
如果没有,请像这样做
因为Android Documentation for getMessagesFromIntent(Intent)表示它只能从API 19开始使用 因此告诉你两种方法从收到的短信中提取发件人的电话号码和信息
getMessagesFromIntent(Intent)
方法onRecieve
for(SmsMessage message : Telephony.Sms.Intents.getMessagesFromIntent(intent)) {
if (message == null) {
Log.e(tag, "message is null");
break;
}
smsOriginatingAddress = message.getDisplayOriginatingAddress();
smsDisplayMessage = message.getDisplayMessageBody();
}
Object[] data = (Object[]) bundle.get("pdus");
for (Object pdu : data) {
SmsMessage message = SmsMessage.createFromPdu((byte[]) pdu);
if (message == null) {
Log.e(tag, "message is null");
break;
}
smsOriginatingAddress = message.getDisplayOriginatingAddress();
smsDisplayMessage = message.getDisplayMessageBody();
}
这应该可以正常工作