So this is my BroadcastReceiver
public class IncomingSMSListener extends BroadcastReceiver {
private static final String SMS_EXTRA_NAME = "pdus";
@Override
public void onReceive(Context context, Intent intent) {
SmsMessage[] messages = fetchSMSMessagesFromIntent(intent);
}
private SmsMessage[] fetchSMSMessagesFromIntent(Intent intent) {
ArrayList<SmsMessage> receivedMessages = new ArrayList<SmsMessage>();
Object[] messages = (Object[]) intent.getExtras().get(SMS_EXTRA_NAME);
for (Object message : messages) {
SmsMessage finalMessage = SmsMessage
.createFromPdu((byte[]) message);
receivedMessages.add(finalMessage);
}
return receivedMessages.toArray(new SmsMessage[0]);
}
}
I'm being able to read the incoming message just fine and all, but let's say from here I want to forward the message to another phone number and make sure it got sent. I know I can do SmsManager.sendTextMessage()
but how do I set up the PendingIntent
part to be notified whether the SMS got sent or not?
OK, ended up finding the solution in the end. Since the context passed in to the onReceive() method in the BroadCastReceiver doesn't let me register other BroadcastReceivers to listen for the "message sent" event, I ended up getting a grip of the app context and doing what follows:
In the BroadcastReceiver:
SmsManager smsManager = SmsManager.getDefault();
Intent intent = new Intent(SENT_SMS_FLAG);
PendingIntent sentIntent = PendingIntent.getBroadcast(context, 0,
intent, 0);
SMSForwarderApp.getAppContext().registerReceiver(
new MessageSentListener(),
new IntentFilter(SENT_SMS_FLAG));
smsManager.sendTextMessage("Here goes the destination of the SMS", null,
"Here goes the content of the SMS", sentIntent, null);
SENT_SMS_FLAG is simply a static string that uniquely identifies the intent I just made. My MessageSentListener looks like this:
public class MessageSentListener extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
int resultCode = this.getResultCode();
boolean successfullySent = resultCode == Activity.RESULT_OK;
//That boolean up there indicates the status of the message
SMSForwarderApp.getAppContext().unregisterReceiver(this);
//Notice how I get the app context again here and unregister this broadcast
//receiver to clear it from the system since it won't be used again
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With