1

asynctask用来执行一些任务。我还想实现在 60 秒内完成,否则会发出超时异常消息。

所以我正在使用AsyncTask.get(time,timeFormat);

例子:

new Thread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    try {
                        validateConnection.execute().get(60, TimeUnit.SECONDS);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    } catch (TimeoutException e) {
                        stopConnTask();
                        invalidCrediantialsError(Utilities.TIMED_OUT_ERROR);
                        e.printStackTrace();
                    }catch(CancellationException e){
                        e.printStackTrace();
                    };
                }
            }).start();

它可以正常工作AsyncTask。在线程中获取块,UI所以我在单独的thread. 这种方法是否正确,或者我必须考虑其他事情。

4

2 回答 2

1
public final Result get ()

Added in API level 3
Waits if necessary for the computation to complete, and then retrieves its result.

Returns
The computed result.
Throws
CancellationException   If the computation was cancelled.
ExecutionException  If the computation threw an exception.
InterruptedException    If the current thread was interrupted while waiting.

调用get()不会使 asynctask 异步。get()等待结果阻塞 ui 线程。删除get()并使用执行,例如new TheTask().execute()

还必须在 ui 线程上调用 asynctask

于 2013-10-10T07:06:13.887 回答
1

AsyncTask 主要用于长时间运行的任务,这些任务会导致 UI 线程中的 ANR 并将其结果报告给用户界面。

If your task runs up to 60 sconds, this means your activity should stay open the same time. Do you really want this? Or don't you need to apply any results to the UI?

In any case, I'd recommend to use a service having a thread inside. You could either start an intent from that service or send a broadcast for further processing by the user interface.

p.s. this post gives some idea in which case AsyncTask.get(...) might make sense: basically said, only if your AsyncTask is doing some initialization that is a kind of fundament for the for the UI.

p.p.s: have you considered to specify a JDBC connection timeout? Check for instance this site for more details.

于 2013-10-10T07:12:53.883 回答