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

查看:168
本文介绍了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?

推荐答案

是的,有<一个href="http://developer.android.com/reference/android/os/AsyncTask.html#get%28long,%20java.util.concurrent.TimeUnit%29">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.

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

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