仅将数据短信接收到一个端口

时间:2016-08-03 14:54:37

标签: android sms android-broadcastreceiver

我的接收器是清单:

<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"/>无法正常工作.. 有什么建议吗?

1 个答案:

答案 0 :(得分:0)

您需要为host上的<data>指定<intent-filter>,并schemehostport需要全部在一个<data>元素中。

建议在permission上添加<receiver>以防止欺骗。

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