可以OnPostExcecute在AsyncTask的返回值的方法?返回值、方法、OnPostExcecute、AsyncTask

2023-09-05 03:43:24 作者:扶你上要

我开发一个Android应用程序需要使用的AsyncTask 网络连接。我从主线程调用它。所以在 doInBackground 方式运行,然后返回到 onPostExecute 方式。在执行onPostExecute方法后,我想返回一个值回从那里它被称为活性,因为我要在那个特定的活动有一定的操作,需要从onPostExecute方法的返回值。 我该如何解决这个问题?如何从onPostExecute返回一个值?

I am developing an Android application which requires the use of AsyncTask for Network connection. I called it from the main thread. So the doInBackground method runs and then returns to the onPostExecute method. After the onPostExecute method is executed, I want to return a value back to the activity from where it was called, as I have to some operation in that particular activity which requires the value returned from onPostExecute method. How do I solve this? How do I return a value from onPostExecute ?

在此先感谢

推荐答案

AsyncTask的,正如它的名字所说,是用异步UI线程运行时,onPostExecute方法将被调用在未来的某个时刻,当doInBackground完成。我们不关心,当onPostExecute方法将被调用(实际上是没有办法告诉在项目建设时间),我们关心的唯一事情就是onPostExecute方法是保证在未来的某一时刻正确地调用底层框架。所以onPostExecute方法的目的是为了从工作线程返回处理结果,这也是为什么onPostExecute方法的唯一参数是结果从doInBackground方法返回。

AsyncTask, as its name stated, is running asynchronously with UI thread, the onPostExecute method will be called at some point in the future, when doInBackground finished. We don't care when onPostExecute method will be called (actually there is no way to tell at project build time), the only thing we care is onPostExecute method is guaranteed to be called properly by underlying framework at some point in the future. So the purpose of onPostExecute method is for processing result returned from worker thread, this is also why the only argument of onPostExecute method is the result returned from doInBackground method.

我要在那个特定的活动有一定的操作,需要从onPostExecute方法的返回值。我该如何解决这个问题?

I have to some operation in that particular activity which requires the value returned from onPostExecute method. How do I solve this?

原因,你可以创建一些实例变量(或使用listerner模式)返回,并准备在onPostExecute方法时,在活动类商店的结果。问题是,你永远不知道什么时候这个结果可以onPostExecute方法外,在项目建设的时间,因为它是在应用程序运行时实际确定。除非你不断地写一些等待投票机制的结果,这导致牺牲的AsyncTask的利益,比如,内置的API AsyncTask.get()这使得AsyncTask的同步运行与UI线程,并将结果返回到活动。

Of cause, you can create some instance variables (or use listerner pattern) in the Activity class store the result when returned and ready in onPostExecute method. The problem is you never know when this result is ready outside onPostExecute method at project build time, as it is actually determined at app runtime. Unless you write some waiting mechanism continuously polling the result, which resulting sacrifice the benefit of AsyncTask, for instance, the built-in API AsyncTask.get() which makes AsyncTask running synchronously with UI thread and return the result to the Activity.

最好的做法是改变设计,移动操作code这需要从AsyncTask的返回到onPostExecute方法的结果。希望这有助于。

The best practice is change your design and move the operation code which requires the result returned from AsyncTask into onPostExecute method. hope this helps.

 
精彩推荐
图片推荐