如何等待发送过程

时间:2014-08-10 09:27:45

标签: java android mobile smsmanager

我正在尝试开发一个Android应用程序,它通过SMS以给定的时间间隔发送GPS坐标。 所以我设置了我的主要活动,允许用户以分钟为单位输入特定时间。将其转移到alarmReceiver。每个警报都会请求locationupdate。 onlocationChanged会在通过短信发送之前将其保存到数据库中。我在发送之前将其保存到数据库中,这样如果发送失败,我将不会丢失任何数据。我正在发送这样的消息:

    dbcon = new SQLController(ctx);         
    dbcon.open();
    String SENT = "SMS_SENT";                       
    final Cursor C = dbcon.readData_Location();

    if(C.moveToFirst()){
        getid = C.getString(0);
        getLongitude = C.getString(1);
        getLatitude = C.getString(2);
        getTime = C.getString(3);
        int id = Integer.valueOf(getid);
        String phoneNo = "09061265887";
        String msg = getLongitude +","+getLatitude+","+getTime;
        Intent sendIntent = new Intent(SENT);
        sendIntent.putExtra("loc_id", id);
        PendingIntent sentPI = PendingIntent.getBroadcast(ctx, 0, sendIntent,0);
        MainActivity.sendTextMessage(phoneNo, null, msg, sentPI, null);

     }while(C.moveToNext());

这里的问题是,它会不断地从数据库中发送所有已保存的位置。 我的计划是,如果第一次发送失败,则必须停止使用do-while循环的发送。 我需要等待并在发送另一个之前检查发送过程的结果。我在这里库存,我不知道该做什么。请帮忙

MainActivity

public class MainActivity extends ActionBarActivity {

EditText et_timeinterval;
Button start,stop;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    et_timeinterval= (EditText) findViewById(R.id.editText1);                        
    start = (Button) findViewById(R.id.button1); 
    stop = (Button) findViewById(R.id.button2); 

    start.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            int timeinminute = Integer.valueOf(et_timeinterval.getText().tostring());
            Intent intent = new Intent(getBaseContext(),alarmReceiver.class);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), timeinminute * 60 * 1000, pendingIntent);
            Toast.makeText(ctx, "Alarm Started", Toast.LENGTH_SHORT).show();                
        }
    });             
}
public static void sendSMS(String phoneNumber,String message) {    
  SmsManager smsManager = SmsManager.getDefault();        

    String SENT = "SMS_SENT";                            

      PendingIntent sentPI = PendingIntent.getBroadcast(basecontext, 0, new Intent(SENT), 0);          
      // ---when the SMS has been sent---
      basecontext.registerReceiver(new BroadcastReceiver() {
          @Override
          public void onReceive(Context arg0, Intent arg1) {                  
              switch (getResultCode()) {
              case Activity.RESULT_OK:
                  Toast.makeText(basecontext, "SMS sent",
                          Toast.LENGTH_SHORT).show();

                  break;
              case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                  Toast.makeText(basecontext, "Generic failure",
                          Toast.LENGTH_SHORT).show();

                  break;
              case SmsManager.RESULT_ERROR_NO_SERVICE:
                  Toast.makeText(basecontext,"No Service",Toast.LENGTH_SHORT).show();

                  break;
              case SmsManager.RESULT_ERROR_NULL_PDU:                        
                  Toast.makeText(basecontext, "Null PDU",
                          Toast.LENGTH_SHORT).show();                           
                  break;
              case SmsManager.RESULT_ERROR_RADIO_OFF:
                  Toast.makeText(basecontext, "Radio off",
                          Toast.LENGTH_SHORT).show();                           
                  break;
              }
          }
      }, new IntentFilter(SENT));
      // ---when the SMS has been delivered---         
      smsManager.sendTextMessage(phoneNumber, null, message, sentPI, null);                     
  }
}

alarmReceiver.java

public class alarmReceiver extends BroadcastReceiver implements LocationListener{
private LocationManager locationManager;
private Context ctx; 
SQLController dbcon;
String latitude,longitude,time;

@Override
public void onReceive(Context context, Intent arg1) {
    // TODO Auto-generated method stub
    ctx =context;
    locationManager = (LocationManager) context
            .getSystemService(Context.LOCATION_SERVICE);        
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1,1,this);                 
}

@Override
public void onLocationChanged(Location location) {
    // TODO Auto-generated method stub

    Time currentTime = new Time(Time.getCurrentTimezone());
    currentTime.setToNow();
    String latitude = ""+location.getLatitude();
    String longitude = ""+location.getLongitude();
    String time = currentTime.format("%k:%M:%S");
    //inserting to database
    dbcon= new SQLController(ctx);
    dbcon.open();
    dbcon.insertData(latitude, longitude, time);

    //sending
    String SENT = "SMS_SENT";                       
    Cursor C = dbcon.readData_Location();       
    if(C.moveToFirst()){
        String getid = C.getString(0);
        String getLongitude = C.getString(1);
        String getLatitude = C.getString(2);
        String getTime = C.getString(3);

        int id = Integer.valueOf(getid);
        String phoneNo = "09061265887";
        String msg = getLongitude +","+getLatitude+","+getTime;
        MainActivity.sendSMS(phoneNo,msg);


     }while(C.moveToNext());
    locationManager.removeUpdates(this);
    dbcon.close();

}

我想做这样的事情

int result_code; //i want to get the resultcode from getResultCode()
C.moveToFirst();
do{
   sendSMS(phonenum,sms);
   //check first if sendSMS sending process is done before the next loop
}while(C.moveToNext() && result_code==0)          
// result code  0 = send success 1=generic failure etc etc

1 个答案:

答案 0 :(得分:1)

这不是一个简单的问题。首先,因为您需要等待,所以需要在后台线程上执行此操作(使用AsyncTask或简单线程)。其次,如果您希望在用户退出活动后继续尝试/操作,您将需要一项服务。

那就是说,你已经有了代码来检查"发送"消息的PendingIntent。您需要您的线程/服务等待广播接收器响应发送的消息以获得响应。

在你的" sendSMS"方法,您正在注册广播接收器以侦听SMS发送的状态。它会告诉您发送是否成功,然后您可以继续发送位置更新,再试一次或其他。

像这样:

  basecontext.registerReceiver(new BroadcastReceiver() {
      @Override
      public void onReceive(Context arg0, Intent arg1) {                  
          switch (getResultCode()) {
          case Activity.RESULT_OK:
              Toast.makeText(basecontext, "SMS sent",
                      Toast.LENGTH_SHORT).show();

              // add code here to send next message

              break;
          case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
              Toast.makeText(basecontext, "Generic failure",
                      Toast.LENGTH_SHORT).show();

              // add code here to try again or wait

              break;
          case SmsManager.RESULT_ERROR_NO_SERVICE:
              Toast.makeText(basecontext,"No Service",Toast.LENGTH_SHORT).show();

              // add code here to try again or wait

              break;
          case SmsManager.RESULT_ERROR_NULL_PDU:                        
              Toast.makeText(basecontext, "Null PDU",
                      Toast.LENGTH_SHORT).show();                           

              // add code here to try again or wait

              break;
          case SmsManager.RESULT_ERROR_RADIO_OFF:
              Toast.makeText(basecontext, "Radio off",
                      Toast.LENGTH_SHORT).show();                           

              // add code here to try again or wait

              break;
          }
      }
  }, new IntentFilter(SENT + someMessageId));

如果您在等待接收方回复之前发送多条短信,您的意图过滤器还需要识别该消息(我添加的位置" someMessageId")。