somerandomusername somerandomusername - 10 months ago 67
Android Question

Receiving and sending SMS in one BroadcastReceiver (Android)

I'm trying to set up one class for receiving sms and sent status.
This is how my manifest looks for this task:

<receiver android:name=".SmsListener" android:permission="android.permission.BROADCAST_SMS" android:exported="true">
<intent-filter android:priority="5822">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
<action android:name="android.provider.Telephony.SMS_SENT" />

I get received messages, but don't get SENT messages, is something wrong with my Manifest declarations?

PendingIntent _pendingIntent;
Intent _intent = new Intent();
_intent.setClass(ParkingOptionsActivity.this, SmsListener.class); // SmsListener extends BroadcastReceiver
_pendingIntent = PendingIntent.getActivity(ParkingOptionsActivity.this, 0, _intent, 0);
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, "test message", _pendingIntent, null);

Answer Source

You need to obtain your PendingIntent with getBroadcast() instead of getActivity(), since you want to send a broadcast to your BroadcastReceiver, not start an Activity.

In your current code, you can simply change that one line:

_pendingIntent = PendingIntent.getBroadcast(ParkingOptionsActivity.this, 0, _intent, 0);

Furthermore, the "android.provider.Telephony.SMS_SENT" action is not present in the SDK currently, and there is no system broadcast when an SMS is sent. Your app doesn't really need that <action> in the manifest entry, since the Intent is explicitly targeting your Receiver class.

If you do plan to use that action for something else - e.g., differentiating broadcasts in onReceive(), receiving implicit broadcasts from other apps, etc. - then you might consider changing it to use something other than the android.provider.Telephony package name, so as not to cause potential unwanted behavior or confusion in the future. Using your own app's package name is the norm, I would say.