【问题标题】:Android repeating task with timeout in JavaJava中超时的Android重复任务
【发布时间】:2016-06-17 11:53:48
【问题描述】:

我有重复任务的问题。

基本上,我正在开发服务,它会发送短信并检查一分钟的响应。如果收到响应,我会使用成功消息更新 textview,否则会失败。 我的发送短信服务工作正常,但我一直无法接收短信。 我打电话给发送短信并像这样检查短信:

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 秒超时。如果收到短信,我应该更新 textview 成功,如果没有,我会等到超时并设置 textview 失败。

【问题讨论】:

  • 查看专为 Android 后台操作而设计的 AsyncTask
  • 在线程内执行 Thread.sleep(1000*60)。这将使线程等待 60 秒的时间段,然后检查是否收到短信。
  • 使用倒计时

标签: java android concurrency


【解决方案1】:

你可以做的是:

  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

注意:线程池不能在每次调用时创建,它必须在你的类中创建一次,以便在每次调用时重用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-15
    • 1970-01-01
    • 1970-01-01
    • 2011-01-31
    • 1970-01-01
    • 1970-01-01
    • 2017-05-09
    相关资源
    最近更新 更多