0

I am trying to send multiple SMS messages from an AsyncTask inside a Service, the problem is that I want to check if the SMS messages were delivered successfully or not but the AsyncTask will finish once the doInBackground method returns, how to send multiple SMS messages and check the delivery result?

Here is my code:

class SendSmsMessages extends AsyncTask<Void, Void, Void> {

    private final ArrayList<String> messages;

    public SendSmsMessages(ArrayList<String> messages) {
        this.messages = messages;
    }

    @Override
    protected Void doInBackground(Void... param) {
        for (String message : messages) {
            try {
                Intent intent = new Intent("send_message");
                PendingIntent pendingIntent = PendingIntent.getBroadcast(MessagesService.this, 0, intent, 0);
                MessagesService.this.registerReceiver(new BroadcastReceiver() {
                    @Override
                    public void onReceive(Context context, Intent intent) {
                        if (getResultCode() == RESULT_OK) {
                            //Messages were sent clear the database
                        }
                    }
                }, new IntentFilter("send_message"));
                SmsManager smsManager = SmsManager.getDefault();
                smsManager.sendTextMessage(MessagesService.this.phoneNumber, null, message, pendingIntent, null);
            } catch (Exception ex) {
                Log.d(TAG, "Failed to send sms: " + ex.getMessage());
                ex.printStackTrace();
            }
        }
        return null;
    }
}
David Wasser
  • 93,459
  • 16
  • 209
  • 274
Waxren
  • 2,002
  • 4
  • 30
  • 43
  • "...but the AsyncTask will finish once the doInBackground method returns" - I'm not sure why that's a problem. The `AsyncTask` shouldn't be what's handling the Receiver for your `"send_message"` broadcast. – Mike M. Aug 08 '17 at 19:31
  • @MikeM. I need a reference to the message variable so I can delete it from the database, and I can't send that variable with the intent passed to the pending intent because of this: https://stackoverflow.com/a/25173018/4231826 – Waxren Aug 09 '17 at 03:19
  • "...I can't send that variable with the intent..." - Sure ya can. The second parameter in `getBroadcast()` is a request code that can be used to generate new `PendingIntent`s for each. That is, instead of passing `0` each time, use a unique request code for each. A simple incrementing counter is sufficient. Also, you don't really need to register a new `BroadcastReceiver` for every message. You can register just one to handle them all, since that action is always the same. And, be sure to check the result code in the Receiver to make sure a message was actually sent, before you delete it. – Mike M. Aug 09 '17 at 03:40

0 Answers0