2016-09-27 190 views
1

我想創建應用程序,可以從端口接收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

+1

數據短消息中不會有消息正文。使用'SmsMessage#getUserData()'方法檢索數據,數據將採用'byte'數組的形式,如上面鏈接文章的接受答案中所示。 –

+0

tnx!那就對了! –

回答

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); 

    } 
}  

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類解密。

+1

不!在你的代碼中,消息是空的! :( –

+0

TNX Milad!現在,我可以從data = recMsg.getUserData()獲取字節數組,但recMsgString具有Byte Format!和新的String(數據,「UTF-8」)不起作用:| –

+0

recMsgString被定義爲(int index = 0; index