Android重复任务与Java的超时任务



我对重复任务有问题。

基本上,我正在为服务发送SMS并检查一分钟的响应。如果收到响应,我会更新带有成功消息的文本视图,否则会失败。我的发送短信服务正常,但我一直待在接收SMS上。我致电发送短信,然后检查SMS:

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

这是readSms

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

如何使readSms使用1秒间隔等待60秒的超时。如果收到的SMS,我应该成功地更新文本视图,如果不是,我将等到超时并设置fafe。

您可以做的是:

  1. 创建一个线程池
  2. 将您的任务作为Callable提交到线程池
  3. 等待一分钟的结果

使用这样的Executors创建线程池:例如:

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

将您的任务提交为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);
        }
    }
});

等待一分钟的结果

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

如果无法在1分钟内检索结果,则get方法将抛出TimeoutException

nb:不得在每个呼叫上创建线程池,必须在班级中创建一次,以便在每个呼叫中重复使用它。

最新更新