AsyncTask的返回值 [英] AsyncTask return value

查看:190
本文介绍了AsyncTask的返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Andr​​oid应用程序,连接到我的网站检索和上传信息,所以我用一个AsyncTask的主题。

My android app connects to my website to retrieve and upload information so I use an AsyncTask thread.

在一种情况下,我需要我的线程返回一个true或false值给我的主线程。

In one instance, I need my thread to return a true or a false value to my main thread.

有没有办法让从AsyncTask的这个返回值执行的功能?

Is there a way to get this return value from an AsyncTask execute function?

当我做到以下几点:

Toast.makeText(Locate.this, "Testing : "+locationUpdate.execute(location), Toast.LENGTH_LONG).show();

我刚刚得到的废话很多。

I just get alot of gibberish.

我想我需要的是暂停主线程,直到第二个线程完成一个手段。第二个线程调用在主线程设置我的返回值的函数。 第二个线程完成所以,当主线程可以取消暂停和第二线的设置访问返回值 如果这个逻辑是健全的,请提供建议...谢谢!

I think what I need is a means to pause the main thread until the second thread completes. The second thread calls a function in the main thread to set my return value. So when the second thread completes, the main thread can unpause and access the return value as set by the second thread If this logic is sound, please offer suggestions ... thanks!

推荐答案

您可以使用的AsyncTask的获得()方法这一点。为使计算完成,它等待如果需要的话,然后获取其结果:

You can use AsyncTask get() method for this. It waits if necessary for the computation to complete, and then retrieves its result:

Toast.makeText(Locate.this, "Testing : " + locationUpdate.execute(location).get(), Toast.LENGTH_LONG).show();

但一定要不会阻塞主线程的很长一段时间,因为这将导致无响应的用户界面和的 ANR

更新
我错过了点问题是关于异步网络下载/上传。网络/网络操作应视为一个漫长的,因此该方法的暂停UI线程,等到下载完成的始终是错误的。使用通常的结果发布方式intstead(例如: AsyncTask.onPostExecute ,服务+ sendBroadcast,像排球,RoboSpice,DataDroid等库)。

UPDATE
I missed the point that question was about async web download/upload. Web/network operation should considered as a long one and thus the approach "pause UI thread and wait till download finishes" is always a wrong one. Use usual result publishing approach intstead (e.g.: AsyncTask.onPostExecute, Service + sendBroadcast, libraries like Volley, RoboSpice, DataDroid etc).

这篇关于AsyncTask的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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