从端口接收短信
我想创建应用程序,可以从端口接收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
可以在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);
}
}
OK,如果你已编码的邮件前,你想现在你必须遵循自爆措施来对其进行解码,但如果不只是删除您的整个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
类解密。
不!在你的代码中,消息是空的! :( –
TNX Milad!现在,我可以从data = recMsg.getUserData()获取字节数组,但recMsgString具有Byte Format!和新的String(数据,“UTF-8”)不起作用:| –
recMsgString被定义为(int index = 0; index
数据短消息中不会有消息正文。使用'SmsMessage#getUserData()'方法检索数据,数据将采用'byte'数组的形式,如上面链接文章的接受答案中所示。 –
tnx!那就对了! –