异步任务返回值 [英] AsyncTask return value

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

问题描述

我的 Android 应用连接到我的网站以检索和上传信息,因此我使用了 AsyncTask 线程.

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

在一个例子中,我需要我的线程向我的主线程返回一个真值或假值.

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 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 get() 方法.如果需要,它等待计算完成,然后检索其结果:

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();

但一定不要长时间阻塞主线程,因为这会导致 UI 无响应和 ANR.

But be sure to not block the main thread for a long period of time, as this will lead to unresponsive UI and ANR.

更新
我错过了关于异步网络下载/上传的问题.Web/网络操作应该被认为是一个很长的操作,因此暂停UI线程并等待下载完成"的方法总是错误的.改用通常的结果发布方法(例如:AsyncTask.onPostExecute、Service + sendBroadcast、Volley、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).

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

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