我想创建可以从端口接收SMS
的应用!但是当它运行时,我的msg.getMessageBody()
返回null。我该如何修理它?
manifext.xml
<receiver android:name="data.SMSReceiver" android:enabled="true">
<intent-filter>
<action android:name="android.provider.telephony.SMS_RECEIVED" />
<data android:scheme="sms"
android:host="*"
android:port="4030"/>
</intent-filter>
广播接收器代码
public class SMSReceiver extends BroadcastReceiver {
private static final String SHORTCODE = "+9810004473";
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
Object[] messages = (Object[])bundle.get("pdus");
SmsMessage[] sms = new SmsMessage[messages.length];
for(int n=0; n < messages.length; n++) {
sms[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
}
for(SmsMessage msg : sms) {
if(TextUtils.equals(msg.getOriginatingAddress(), SHORTCODE)) {
Toast.makeText(context, "SMS: " + msg.getMessageBody(), Toast.LENGTH_LONG).show();
}
}
}
}
我的Toast
显示:SMS: null
答案 0 :(得分:0)
您可以将此代码替换为onReceive
中的代码:
// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();
public void onReceive(Context context, Intent intent) {
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
Bundle bundle = intent.getExtras();
String recMsgString = "";
String fromAddress = "";
SmsMessage recMsg = null;
byte[] data = null;
if (bundle != null)
{
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
for (int i=0; i<pdus.length; i++){
recMsg = SmsMessage.createFromPdu((byte[])pdus[i]);
try {
data = recMsg.getUserData();
} catch (Exception e){
}
if (data!=null){
for(int index=0; index<data.length; ++index)
{
recMsgString += Character.toString((char)data[index]);
}
}
fromAddress = recMsg.getOriginatingAddress();
}
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
}
好的,如果你之前编码了你的消息,并且你现在想要解码它,你必须遵循吹嘘的步骤,但如果不是只删除整个onReceive
并替换我的代码。
您在错误的地方解密您的邮件,您必须遵循我写的确切步骤。你必须在这里得到消息(在获得data
之后):
if (data!=null){
for(int index=0; index<data.length; ++index)
{
recMsgString += Character.toString((char)data[index]);
}
}
String decryptedData = Base64.decode(recMsgString ,...)//add this line
在recMsgString
中获取消息字符串后,您可以使用Base64
类对其进行解密。