2016-08-03 60 views
1

我得到了我在清單接收器:接收數據短信到只有一個端口

<receiver android:name=".receiver.SMSReceiver"> 
     <intent-filter> 
      <action android:name="android.intent.action.DATA_SMS_RECEIVED"/> 
      <data android:scheme="sms"/> 
      <data android:port="10013"/> 
     </intent-filter> 
    </receiver> 

和我的接收機類

public class SMSReceiver extends BroadcastReceiver { 

@Override 
public void onReceive(Context context, Intent intent) { 
    final Bundle bundle = intent.getExtras(); 
    SmsMessage[] messages = null; 
    String text = ""; 
    byte[] data = null; 

    if (bundle != null){ 
     Object[] pdus = (Object[]) bundle.get("pdus"); 
     for (int i = 0; i < pdus.length; i++){ 
      messages = new SmsMessage[pdus.length]; 
      messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); 
      String phoneNumber = messages[i].getOriginatingAddress(); 
      try { 
       data = messages[i].getUserData(); 
      } catch (Exception e){ 

      } 
      String hex = byteArrayToHex(data); 
      Toast toast = Toast.makeText(context, 
        "senderNum: "+ phoneNumber + ", message: " + hex, Toast.LENGTH_LONG); 
      Log.d("mylog","senderNum: "+ phoneNumber + ", message: " + text); 
      toast.show(); 
     } 
    } 
} 

public static String byteArrayToHex(byte[] a) { 
    StringBuilder sb = new StringBuilder(a.length * 2); 
    for(byte b: a) 
     sb.append(String.format("%02x", b & 0xff)); 
    return sb.toString(); 
} 

,它工作正常,我收到我的短信數據。 但是,我也收到其他端口的數據短信.. 看起來像過濾器<data android:port="10013"/>不起作用.. 有什麼建議嗎?

回答

0

您需要在<intent-filter>指定<data>一個hostschemehostport需要都在一個<data>元素。

建議在<receiver>上包含permission以防止欺騙。

<receiver android:name=".receiver.SMSReceiver" 
    android:permission="android.permission.BROADCAST_SMS"> 
    <intent-filter> 
     <action android:name="android.intent.action.DATA_SMS_RECEIVED"/> 
     <data 
      android:scheme="sms" 
      android:host="localhost" 
      android:port="10013" /> 
    </intent-filter> 
</receiver> 
+1

現在,它的工作,感謝您的幫助! –