天天看点

android 发送短信 如何做到一条一条的发送,只有在上一条发送成功之后才发送下一条短信

android发送短信截获上一条发送是否成功,然后再来发送下一条短信

1.问题:在项目中遇到如下要求:待发短信有N条,实现一条一条的发送并在上一条短信发送成功之后再来发送下一条。

  for(int i=0;i<3;i++){

  sendSMS(10086, text1, i);

  }

private void sendSMS(String toAddress, String body, Long id) {

// ---sends an SMS message to another device---

                     SmsManager sms = SmsManager.getDefault();

String SENT_SMS_ACTION = "SENT_SMS_ACTION";

// create the sentIntent parameter

Intent sentIntent = new Intent(SENT_SMS_ACTION);

sentIntent.putExtra("id", id);

   PendingIntent sentPI = PendingIntent.getBroadcast(

   ListOutgoingActivity.this, 0, sentIntent, PendingIntent.FLAG_UPDATE_CURRENT); 

//你同时发送很多信息的话,会产生很多一样的PendingIntent,然后Android操作系统会把pendingIntent的数据更新到最新,所以toast的ID是最新的数据,以前的数据会被覆盖掉。这个可以用来同步数据。

// 如果短信内容超过70个字符 将这条短信拆成多条短信发送出去

                    if (body.length() > 70) {

ArrayList<String> msgs = sms.divideMessage(body);

for (String msg : msgs) {

sms.sendTextMessage(toAddress, null, msg, sentPI,

null);

}

} else {

System.out.println("body====" + body);

sms.sendTextMessage(toAddress, null, body, sentPI, null);

BroadcastReceiver sendMessage = new BroadcastReceiver() {

@Override

public void onReceive(Context context, Intent intent) {

// 判断短信是否发送成功

switch (getResultCode()) {

case Activity.RESULT_OK:

Long id = intent.getLongExtra("id", -12);

                                                              //截取每次发送短信的ID,但是toast的id都是2???,正常情况下应该分别是0,1,2

Toast.makeText(ListOutgoingActivity.this,

id +"发送成功", Toast.LENGTH_SHORT).show();

break;

default:

"发送失败", Toast.LENGTH_LONG).show();

};

registerReceiver(sendMessage, new IntentFilter(

SENT_SMS_ACTION));}

2.解决办法:现在的解决方法是,收到上一条信息发送成功或者失败后,在发送下一条数据

int i=0;

sendSMS(10086,test, i) ;

 String SENT_SMS_ACTION = "SENT_SMS_ACTION";

    PendingIntent sentPI = PendingIntent.getBroadcast(

    ListOutgoingActivity.this, 0, sentIntent, PendingIntent.FLAG_UPDATE_CURRENT); 

                                   // 如果短信内容超过70个字符 将这条短信拆成多条短信发送出去

                                    Toast.makeText(ListOutgoingActivity.this,id +"发送成功", Toast.LENGTH_SHORT).show();

i++;

                                             if(i<3){

                                                 sendSMS(10086,test,i)

                                            }