yanie002
yanie002

Reputation: 1

How to wait for a sending process

I'm trying to develop an android application that sends GPS coordinates via SMS with given time interval. So I set up my main activity allowing the user to input a specific time in minutes. Transfer it to a alarmReceiver. Every alarm will request a locationupdate. And onlocationChanged will save it to the database before sending it via sms. I save it to the database before sending so that i will not lost any data if sending fails. I'm sending a message like this :

    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());

The problem here is, it will send all the saved locations from the database continuously. My plan is if the first sending fails, the sending using do-while loop must be stop. I need to wait and check the result of sending process before sending another one. Im stock here and i dont know that to do. please help

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();

}

I want to do something like this

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

Upvotes: 0

Views: 467

Answers (1)

Jim
Jim

Reputation: 10288

This is not a simple problem. First, since you will want to wait, you need to do this on a background thread (using AsyncTask or a simple thread). Second, if you want it to continue trying/operating after the user exits the activity, you will need a service.

That said, you already have the code in place to check for the "sent" PendingIntent for the message. You need your thread/service to wait for the broadcast receiver responde from the sent message to get a response.

In your "sendSMS" method, you are registering a broadcast receiver to listen for the status of the SMS send. It will tell you whether the send was successful or not, and then you can either continue sending location updates, try again or whatever.

Like this:

  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));

Your intent filter also needs to identify the message (where I added "someMessageId") if you send more than one SMS before waiting for the receiver to respond.

Upvotes: 1

Related Questions