Android : Android java : Sending multi sms msgs , registerReceiver inside loop .

on Saturday, November 1, 2014


I am trying about 10 hours to make it works ):


The main idia is when user clicks button the for loop is starting the smsSend msg function and updates the sent msgs for each send.


I am sending starting each sms send inside unique Thread .



  • NOTE : the message is divided cuz of length .


If i am sending the sms to 1 person , the BroadcastReceiver runing twice and msg is sent .


If i am sending the sms to 2 persons , the BroadcastReceiver runing 4 times for each person |:


And only one person recives the message , the other one gets RESULT_ERROR_GENERIC_FAILURE .


What i am doing wrong ? if each function calls in unique Thread , why the BroadcastReceiver works 4 times for each person ? Please help how do i solve this ?


Call to function:



send.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {

final Thread[] threads = new Thread[phoneNumbers.size()];

for (int i=0; i<phoneNumbers.size(); i++){

final int index = i;

threads[i] = new Thread(new Runnable() {
public void run() {
try {
sendSMS(phoneNumbers.get(index).split(",")[1], messageToSent,index);
} catch (UnsupportedEncodingException e) {
}
}
});
threads[i].start();
}
}
});


The function :



public void sendSMS(final String mobNo, String message,final int i) throwsUnsupportedEncodingException {

String smsSent = "SMS_SENT";

SmsManager sm = SmsManager.getDefault();
ArrayList<String> parts =sm.divideMessage(message);
final int numParts = parts.size();

registerReceiver(new BroadcastReceiver(){
int numberOfRecives=0;
boolean msgSent;

@Override
public void onReceive(Context arg0, Intent arg1) {

numberOfRecives+=1;
if(numberOfRecives==numParts && msgSent){

Send.this.runOnUiThread(new Runnable() {

@Override
public void run() {
Toast.makeText(Send.this,"message is sent", Toast.LENGTH_LONG).show();
}
});


}

switch (getResultCode()){

case Activity.RESULT_OK:
msgSent=true;
break;

case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
msgSent=false;
break;

case SmsManager.RESULT_ERROR_NO_SERVICE:
msgSent=false;
break;

case SmsManager.RESULT_ERROR_NULL_PDU:
msgSent=false;
break;

case SmsManager.RESULT_ERROR_RADIO_OFF:
msgSent=false;
break;
}
}
}, new IntentFilter(smsSent));

ArrayList<PendingIntent> sentIntents = new ArrayList<PendingIntent>();

for (int j = 0; j < numParts; j++) {
sentIntents.add(PendingIntent.getBroadcast(this, 0, new Intent(smsSent), 0));
}

sm.sendMultipartTextMessage(mobNo,null, parts, sentIntents, null);
}


Thanks you very much !


0 comments:

Post a Comment