I'm trying to send SMS messages to contacts when a broadcast receiver is triggered, but the method for sending SMS messages seems that its not working in the broadcast receiver(its working fine in the activity) - its sending SMS only to the first contact, and then it stops. Can someone check my code and tell me what can the issue be?
Note: im not getting any error or warning in LogCat. Im calling this in the on receiver method that is called(checked that works) and it sending SMS only to the first contact, but not to the rest.
Here is my code:
private void sendSMS(String message) {
ArrayList<Contact> contacts = getContacts();
Log.d(TAG, "sengind SMS message, contacts size: " + contacts.size());
for (Contact contact : contacts) {
try {
sendSMSmsg(contact.getNumber(), message);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void sendSMSmsg(String phoneNumber, String message) {
v.vibrate(50);
ArrayList<PendingIntent> sentPendingIntents = new ArrayList<PendingIntent>();
ArrayList<PendingIntent> deliveredPendingIntents = new ArrayList<PendingIntent>();
PendingIntent sentPI = PendingIntent.getBroadcast(context, 0,
new Intent(context, SmsSentReceiver.class), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(context, 0,
new Intent(context, SmsDeliveredReceiver.class), 0);
try {
SmsManager sms = SmsManager.getDefault();
ArrayList<String> mSMSMessage = sms.divideMessage(message);
for (int i = 0; i < mSMSMessage.size(); i++) {
sentPendingIntents.add(i, sentPI);
deliveredPendingIntents.add(i, deliveredPI);
}
sms.sendMultipartTextMessage(phoneNumber, null, mSMSMessage,
sentPendingIntents, deliveredPendingIntents);
} catch (Exception e) {
Log.e(TAG, "sending sms ERROR");
e.printStackTrace();
}
}
Its a common behavior of BroadcastListener. You should not use it for such tasks. You better make a Service or IntentService and start a SMS sending job in it from your BroadcastListener. That way it should work.