简体   繁体   English

如何知道异步任务何时完成

[英]how to know when asynctask is finished

public class Calculate extends AsyncTask<Void, Integer, Integer> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Integer doInBackground(Void... arg0) {
        int a = 1;
                int b = 2

        return a+b;
    }

    @Override
    protected void onPostExecute(Integer result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);

    }

}

my app use asynctask class (below), and a function to call this class, my question is how to know when this class is finished ? 我的应用程序使用asynctask类(如下)和一个调用此类的函数,我的问题是如何知道此类何时完成? every time i check, its always Running ! 每次检查时,它始终在运行!

In your onPostExecute(...) method, you could simply call a method in your caller Activity which would set a boolean terminated_activity to true . 在您的onPostExecute(...)方法中,您可以简单地在调用方Activity调用一个方法,该方法会将boolean terminated_activity onPostExecute(...)设置为true You can do this in several ways, most probably the easiest ones are Intents combined with a Handler , or a local BroadcastReceiver . 您可以通过多种方式执行此操作,最可能最简单的方法是将IntentsHandler或本地BroadcastReceiver结合使用。

  • An example on Handler s and Intent s is in an answer I posted today in other question, here . 关于HandlerIntent的一个例子是我今天在另一个问题此处发布的答案。
  • A nice explaination on local BroadcastReceiver s is here . 关于本地BroadcastReceiver的一个很好的解释在这里

onPostExecute(Result), invoked on the UI thread after the background computation finishes. onPostExecute(Result),在后台计算完成后在UI线程上调用。 The result of the background computation is passed to this step as a parameter. 后台计算的结果作为参数传递到此步骤。

Directly from the docs 直接从文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM