Android发送短信接收器运行两次

时间:2014-10-24 17:57:30

标签: android sms

我使用循环让android从json数据集发送了几条消息,并在短信成功发送时使用广播接收器来制作日志。

但不知何故,当我这样做时,日志不止一次运行, 记录1 - 记录一次, 记录2 - 记录两次, 记录3 - 记录3次。

为什么它表现得那样?

这是我的循环

for (int i = 0; i < nodeData.length(); i++) {
            JSONObject row = nodeData.getJSONObject(i);
            id = row.getInt("id");
            phone = row.getString("phone");
            message = row.getString("message");

            doSendMessage(phone, message);
        }    

这是我的发送短信代码

protected void doSendMessage(String phone, String message){
    String SENT = "Message Sent";
    String DELIVERED = "Message Delivered";

    MainActivity.phone = phone;
    MainActivity.message = message;

    Intent inSent = new Intent(SENT);
    Intent inDelivered = new Intent(DELIVERED);

    inSent.putExtra("exPhone", phone);
    inSent.putExtra("exMessage", message);

    PendingIntent piSent = PendingIntent.getBroadcast(this, 0, inSent, PendingIntent.FLAG_UPDATE_CURRENT);
    PendingIntent piDelivered = PendingIntent.getBroadcast(this, 0, inDelivered, 0);

    registerReceiver(new BroadcastReceiver(){
        public void onReceive(Context arg0, Intent arg1){    
            switch(getResultCode()){
                case Activity.RESULT_OK:
                    Toast.makeText(MainActivity.this, "SMS Sent", Toast.LENGTH_LONG).show();

                    Bundle extras = arg1.getExtras();               
                    if (extras != null) {
                      String exPhone = (String) extras.get("exPhone");
                      String exMessage = (String) extras.get("exMessage");
                      //Log.i("test_asd", exPhone + "-" + exMessage );
                      doSaveInOutbox(exPhone, exMessage);
                    }
                    break;
                case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                    Toast.makeText(getBaseContext(), "Generic Failure", Toast.LENGTH_LONG).show();
                    break;
                case SmsManager.RESULT_ERROR_NO_SERVICE:
                    Toast.makeText(getBaseContext(), "No Service", Toast.LENGTH_LONG).show();
                    break;                      
            }
        }
    }, new IntentFilter(SENT));

    registerReceiver(new BroadcastReceiver(){
        public void onReceive(Context arg0, Intent arg1){
            switch(getResultCode()){
                case Activity.RESULT_OK:
                    Toast.makeText(getBaseContext(), "SMS Delivered", Toast.LENGTH_LONG).show();
                    break;
                case Activity.RESULT_CANCELED:
                    Toast.makeText(getBaseContext(), "SMS Not Delivered", Toast.LENGTH_LONG).show();
                    break;  
            }
        }
    }, new IntentFilter(DELIVERED));

    SmsManager sms = SmsManager.getDefault();
    sms.sendTextMessage(phone, null, message, piSent, piDelivered);
}

0 个答案:

没有答案