Android-为AsyncTask设置超时?

我有一个AsyncTask要执行的类,该类从网站下载大量数据。


如果最终用户在使用时数据连接速度非常慢或参差不齐,我想AsyncTask在一段时间后超时。我的第一个方法是这样的:


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,一个新的处理程序被启动,将取消AsyncTask30秒后,如果它仍在运行。


这是一个好方法吗?还是内置一些AsyncTask更适合此目的的东西?


FFIVE
浏览 1106回答 3
3回答

三国纷争

是的,有AsyncTask.get()myDownloader.get(30000, TimeUnit.MILLISECONDS);请注意,通过在主线程(AKA.UI线程)中调用此函数将阻止执行,您可能需要在单独的线程中调用它。

慕容森

在这种情况下,您的下载器基于URL连接,您有许多参数可以帮助您定义超时而无需复杂的代码:  HttpURLConnection urlc = (HttpURLConnection) url.openConnection();  urlc.setConnectTimeout(15000);  urlc.setReadTimeout(15000);如果仅将此代码带入异步任务中,就可以了。“读取超时”是在整个传输过程中测试不良网络。仅在开始时调用“连接超时”以测试服务器是否启动。

慕桂英4014372

在onPreExecute()方法中,在AsyncTask扩展类的旁边使用CountDownTimer类:主要优点是,异步监视在类内部完成。public class YouExtendedClass extends AsyncTask<String,Integer,String> {...public YouExtendedClass asyncObject;&nbsp; &nbsp;// as CountDownTimer has similar method -> to prevent shadowing...@Overrideprotected void onPreExecute() {&nbsp; &nbsp; asyncObject = this;&nbsp; &nbsp; new CountDownTimer(7000, 7000) {&nbsp; &nbsp; &nbsp; &nbsp; public void onTick(long millisUntilFinished) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // You can monitor the progress here as well by changing the onTick() time&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; public void onFinish() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // stop async task if not in progress&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (asyncObject.getStatus() == AsyncTask.Status.RUNNING) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; asyncObject.cancel(false);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Add any specific task you wish to do as your extended class variable works here as well.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }.start();...更改CountDownTimer(7000,7000)-> CountDownTimer(7000,1000)例如,它将在调用onFinish()之前调用onTick()6次。如果要添加一些监视,这很好。感谢您在此页面中提供的所有好的建议:-)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Android
Java