user965071
user965071

Reputation: 1683

Unable to receive sms in my android application

I am trying to receive the sms from a particular number in my android application and trying to show the message content in my application. But i am not able receive the sms.

the class which i am using to receive is given below.

public class SmsReceiver extends BroadcastReceiver {

StringBuilder sb;

@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction()
            .equals("android.provider.Telephony.SMS_RECEIVED")) {

        Bundle extras = intent.getExtras();
        if (extras != null) {
            Object[] pdus = (Object[]) extras.get("pdus");

            if (pdus.length < 1)
                return; // Invalid SMS. Not sure that it's possible.

            sb = new StringBuilder();
            String sender = null;
            for (int i = 0; i < pdus.length; i++) {

                SmsMessage message = SmsMessage
                        .createFromPdu((byte[]) pdus[i]);
                if (sender == null)
                    sender = message.getOriginatingAddress();

                String text = message.getMessageBody();
                if (text != null)
                    sb.append(text);
            }
            if (sender != null && sender.equals("********")) {
                // Process our sms...

                Intent broadcastIntent = new Intent();
                broadcastIntent.setAction("SMS");

                broadcastIntent.putExtra("data", sb.toString());



                context.sendOrderedBroadcast(broadcastIntent, null);
                System.out.println("MESSAGE FROM SERVER -->"
                        + sb.toString());


                this.abortBroadcast();
            }
            return;
        }
    }
}

}

After receiving the sms, i will check the sender and if it is the sender i am looking for then i will send another broadcast with the sms. There i will show the content.

see my manifest

<receiver android:name=".SmsReceiver" >
        <intent-filter android:priority="2147483647" >
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            <action android:name="SMS" />
        </intent-filter>
    </receiver>

I am not able to find a solution please help.

Upvotes: 1

Views: 551

Answers (1)

Mohsen Afshin
Mohsen Afshin

Reputation: 13436

Things to check (from my experience):

  • android:priority="2147483647" is not valid, the largest value is 1000. Numbers larger than this are ignored
  • Insert your this.abortBroadcast(); in the for loop (to be called pdus.length times)
  • If the sent SMS matches your criteria, for testing, save it in your app preference and in your main activity read the value from your preference, if it worked, then the problem is with your broadcastIntent.

Upvotes: 1

Related Questions