在没有使用 onPostExecute 的情况下使用 AsyncTask 是否有意义?

huangapple go评论84阅读模式
英文:

Does it make sense to use AsyncTask if onPostExcute is not used?

问题

在我查看的代码片段中,使用了一个扩展了 AsyncTask 的私有类。然而,没有使用 onPostExecute 方法。只有 doInBackground 方法被使用,在该方法中进行了一个 POST 请求。我的问题是,AsyncTask 不是用于在执行任务后更新 UI 吗?我的意思是,在没有 onPostExecute 的情况下使用它是否有意义?

(很抱歉,我无法分享代码的任何部分,所以如果这不够清楚,请谅解。)

谢谢。

英文:

in a code snippet I am looking at, a private class which extends AsyncTask is used. However the onPostExecute method is not used. Only the doInBackground method is used and in that method there is a POST request made. The question I have is, isn't AsyncTask is for updating the UI after doing a job? I mean does it make sense to use it without onPostExecute?

(I am not allowed to share any part of the code, so sorry if this is vague.)

Thank you.

答案1

得分: 2

这取决于要执行的任务。您可以完全在不调用onPostExecute的情况下使用AsyncTask,但如果它既不使用onProgressUpdate方法,那么这将意味着错误地使用了其目的,即在后台线程中执行任务,并在UI线程上通知结果,或者在UI线程上通知进度更新。

因此,如果根本不使用onPostExecuteonProgressUpdate,那么可能应该用Thread来替代。

还要考虑,在API 30中已弃用了AsyncTask类,因此现在可能是重构这样的代码的好时机。

英文:

It depends on the task to be performed. You can perfectly use an AsyncTask without calling onPostExecute, but if it doesn't neither use the onProgressUpdate method, then it would mean an incorrect use of its purpose, which is to execute a task in a background thread, and notify the result on the UI thread, or notify progress updates on the UI thread.

So, if is not using onPostExecute or onProgressUpdate at all, then probably should be replaced with a Thread.

Also consider that the AsyncTask class has been deprecated in API 30, therefore may be a good time to refactor such code.

答案2

得分: 0

是的,如果doInBackground方法中的代码没有返回值(仅用于产生副作用),例如在您的情况下用于POST请求,它不会返回值。

根据文档:onPostExecute(Result)在后台计算完成后在UI线程上调用。后台计算的结果作为参数传递给此步骤。

示例:

class DownloadFilesTask extends AsyncTask<Integer, Void, Void>{
 @Override
 protected Void doInBackground(Integer... integers) {
    // 执行POST请求
     return null;
 }
}

因为ProgressResult参数都是Void,所以您不需要重写onPostExecute(Result)方法。

英文:

Yes, If the code in doInBackground method does not return a value (used only for side effect), for example in your case it is used for POST request, Which doses not return a value.

According to Docs: onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.

Example:

class DownloadFilesTask extends AsyncTask&lt;Integer, Void, Void&gt;{
 @Override
 protected Void doInBackground(Integer... integers) {
    //  DO POST REQUEST
     return null;
 }

}

Because the Progress and Result Parameters are Void you don't have to override the onPostExecute(Result) method.

huangapple
  • 本文由 发表于 2020年10月6日 17:00:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/64222543.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定