Android的 - 设置超时时间为AsyncTask的?

Android的 - 设置超时时间为AsyncTask的?

问题描述:

我有我的执行下载数据从一个网站的大名单的的AsyncTask 类。

I have an AsyncTask class that I execute that downloads a big list of data from a website.

在最终用户有在使用的时候非常缓慢或参差不齐的数据连接的情况下,我想了一段之后,使的AsyncTask 超时时间。我的第一个办法,这是像这样:

In the case that the end user has a very slow or spotty data connection at the time of use, I'd like to make the AsyncTask timeout after a period of time. My first approach to this is like so:

MyDownloader downloader = new MyDownloader();
downloader.execute();
Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
  @Override
  public void run() {
      if ( downloader.getStatus() == AsyncTask.Status.RUNNING )
          downloader.cancel(true);
  }
}, 30000 );

启动后的的AsyncTask ,新的处理程序已启动,将取消的AsyncTask 30秒后​​,如果仍运行。

After starting the AsyncTask, a new handler is started that will cancel the AsyncTask after 30 seconds if it's still running.

这是一个好方法?或者是有什么内置的AsyncTask ,更适合用于这一目的?

Is this a good approach? Or is there something built into AsyncTask that is better suited for this purpose?

是的,有AsyncTask.get()

myDownloader.get(30000, TimeUnit.MILLISECONDS);

请注意,通过调用这个主线程(AKA。UI线程)将阻塞执行,你可能需要调用它在一个单独的线程。

Note that by calling this in main thread (AKA. UI thread) will block execution, You probably need call it in a separate thread.