0

The code (android application) I am developing receives an SMS and if the SMS is from a certain number, then it returns a predefined SMS. This all works fine, though I want to add a Timer so that the reply seems realistic. Through a bit of research I have come up with the code below to try and delay the code so that the message sends after 30 second delay.

I define a new timer called Timer1, a delay of 30 seconds and a TimerTask called tt1 at the top, then in the onReceive( ), just before I call the sendSMS method I call the timer() method which starts the timer.

However, the Timer never stops and the message never sends. The app eventually crashes after a few Can anyone see what I am doing wrong?

    static Timer timer1 = new Timer();
static long delay = 30000;
static TimerTask tt1;

        private BroadcastReceiver intentReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

        //---gather up all the necessary user input---
        prefs = getSharedPreferences(prefName, MODE_PRIVATE);
        String textMessage = (String) prefs.getString(NAME_KEY, "");
        final Button btn2 = (Button)findViewById(R.id.btnContacts);
        String phoneNumber = (String) btn2.getText();
        String Sender = (String) intent.getExtras().getString("Sender");

        if(Sender.equals(phoneNumber))
        {
            timer();
            sendSMS(phoneNumber, textMessage); 
        }
        }
    }
     };

        //---holds the delay for realistic reply time---
public static void timer() 
{
    timer1.schedule(tt1 ,0,delay);      
}




//---sends an SMS message to another device---
public void sendSMS(String phoneNumber, String message)
{       
    SmsManager sms = SmsManager.getDefault();
    sms.sendTextMessage(phoneNumber, null, message, null, null);
}

Edit: I am now using handler.postDelayed to pause on sending the text. This works much better

Good beginner resource for handler.postDelayed found here: http://www.appaholics.in/running-a-task-with-a-delay/

Kurt
  • 767
  • 8
  • 23

2 Answers2

0
 what I am doing wrong?

This is where you are wrong

timer1.schedule(tt1 ,0,delay);

The above statement will create a schedule for each 30 second to repeat the sending SMS operation.

I believe you need to reply the SMS to sender one time only, so you need to change your code as follows,

timer1.schedule(tt1 ,100);

Now the above code is going to reply the SMS to sender just one time after 100 mili seconds.

Lucifer
  • 29,392
  • 25
  • 90
  • 143