Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I send an SMS from a BroadcastReceiver and check its status?

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?

like image 474
AxiomaticNexus Avatar asked Aug 15 '11 02:08

AxiomaticNexus


1 Answers

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
}

}

like image 118
AxiomaticNexus Avatar answered Oct 11 '22 18:10

AxiomaticNexus