user3045828 user3045828 - 1 year ago 153
Android Question

Android repeating task with timeout in Java

I've a problem with repeated tasks.

Basically, I'm working on service, which sends sms and check response for a minute. If response received, I update textview with success message otherwise fail.
My send sms service works ok, but I am stuck at receiving the sms.
I call send sms and check sms like this:

sendSms("6617", "Test") // it works;
readSms.run() // it works too;
if (message.equals("desired sms"){ // it doesn't wait read sms to finish
updateTextView("Success");
}
else{
updateTextView("Fail");
}


Here is
readSms
:

Runnable readSms = new Runnable(){
receivedMessage = "";
@Override
public void run() {
try {
//..checking sms..//
if (smsreceived) {message=receivedMessage;}
} finally {
mHandler.postDelayed(readSms, mInterval);
}
}
};


How can I make
readSms
to wait 60 seconds timeout with 1 second interval. If sms received, I should update textview with success, if not I'll wait until timeout and set textview with fail.

Answer Source

What you can do is:

  1. Create a thread pool
  2. Submit your task as a Callable to the thread pool
  3. Wait a minute for a result

Create your thread pool using Executors like this for example:

// Create a thread pool composed of only one thread in this case
ExecutorService executor = Executors.newSingleThreadExecutor();

Submit your task as a Callable

Future<String> result = executor.submit(new Callable<String>(){
    @Override
    public String call() {
        try {
            //..checking sms..//
            if (smsreceived) {return receivedMessage;}
            return null;
        } finally {
            mHandler.postDelayed(readSms, mInterval);
        }
    }
});

Wait a minute for a result

try {
    String receivedMessage = result.get(1, TimeUnit.MINUTES);
} catch (TimeoutException e) {
    // ok let's give up
}

If the result cannot be retrieved within 1 minute the get method will throw a TimeoutException.

NB: The thread pool must not be created at each call, it must be created once for all in your class in order to reuse it at each call.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download