Search code examples
androidsmsandroid-broadcastreceiver

Receiving data sms to only one port


I got my receiver in manifest:

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

and my receiver class

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

And it works fine, I'm receiving my data sms. However, I'm receiving data sms to other ports too.. Looks like filter <data android:port="10013"/> doesn't work.. Any suggestions?


Solution

  • You need to specify a host for the <data> on the <intent-filter>, and the scheme, host, and port need to be all in one <data> element.

    It's also advisable to include a permission on the <receiver> to prevent spoofing.

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