【发布时间】:2015-07-11 21:23:42
【问题描述】:
我正在为 Android 中的主 (UI) 线程寻找一种方法来获取我对网络 SQL 服务器运行的 SQL 查询的结果。
我知道你的第一个答案可能是大喊“ASYNCTASK!!!”,但请耐心等待,我会解释为什么这不是我想要的。
通过使用 AsyncTask,我已经可以毫无问题地运行查询并检索结果。 我正在寻找一种能够将所有这些捆绑到一个调用中的方法,这将返回 AsyncTask 的结果。见下面的伪代码:
public static Object returnQueryResults()
{
// Perhaps show a "Loading" dialog
// Start the AsyncTask that will query the SQL server
// Here is the important part, somehow WAIT for the result
// to be returned or timed out or cancelled or whatever
// return the result gotten by the AsyncTask
}
我知道并完全理解该函数的 WAIT 部分不能是实际的wait(),因为这会阻塞 UI 线程并且 Android 不允许这样做,但我正在寻找的是能够只需要调用这个函数来检索结果。
对我来说,问题似乎是如何将 AsyncTask 的 postExecute 的结果传递给主 UI 线程,同时让 UI 线程等待结果。
任何想法都将不胜感激,因为我已经尝试解决这个问题一段时间了。
【问题讨论】:
-
onPostExecute 总是在主线程上运行。
-
“同时让 UI 线程等待结果”——根据定义,这会阻塞主应用程序(“UI”)线程。当然欢迎您阻塞其他等待 I/O 的线程,但不要阻塞等待 I/O 的主应用程序线程。
-
@BladeCoder 和 @Anand Singh 我非常感谢您对此的想法,但这样做的目的是专门解决在我的整个代码中添加大量 AsyncTask 的需要,这些 AsyncTask 会对网络中的网络造成影响
doInBackground然后在postExecute中针对 UI 进行一些处理。
标签: java android multithreading android-asynctask