Android - 为 AsyncTask 设置超时? [英] Android - Setting a Timeout for an AsyncTask?

查看:39
本文介绍了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);

请注意,通过在主线程(也称为 UI 线程)中调用它会阻止执行,您可能需要在单独的线程中调用它.

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

这篇关于Android - 为 AsyncTask 设置超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆