简体   繁体   English

Android:如果 AsyncTask.execute(new Runnable()) 在方法中被调用,则覆盖 onPostExecute()

[英]Android: override onPostExecute() if AsyncTask.execute(new Runnable()) is invoked in a method

I have a method which I want to execute on a background thread:我有一个要在后台线程上执行的方法:

public class MainActivity extends AppCompatActivity {
     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        foo();
    }

    public static void foo(){
        AsyncTask.execute(() -> {
            // perform some object creations
        });
    }

    public static void foo2(){
      // Method that updates UI (lists and views) which requires the main thread.
    }
}

I would like to execute foo2 when AsynTask is complete ie onPostExecute() .我想在AsynTask完成时执行foo2 ,即onPostExecute() How can I override onPostExecute() in this case?在这种情况下,如何覆盖onPostExecute()

不能直接实现,可以通过扩展Async类来实现。

It may be helpful, You can achieve this by class instead of method.这可能会有所帮助,您可以通过类而不是方法来实现这一点。 Please try the below snippet:请尝试以下代码段:

@Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      foo asyncTask=new foo();
      asyncTask.execute();

   }

private class foo extends AsyncTask<void, void, void> {
      @Override
      protected void onPreExecute() {
         super.onPreExecute();

      }
      @Override
      protected void doInBackground(String... strings) {

      }
      @Override
      protected void onPostExecute() {
         super.onPostExecute();
         foo2 asyncTask=new foo2();
         asyncTask.execute();
      }
   }

private class foo2 extends AsyncTask<void, void, void> {
      @Override
      protected void onPreExecute() {
         super.onPreExecute();

      }
      @Override
      protected void doInBackground(String... strings) {

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

      }
   }

It's Work For me这对我有用

public class MyTask extends AsyncTask<String, Void, String>
{
    @Override
    protected Void doInBackground(String... params) {
        //Do background 
    }

    protected void onPostExecute() {
        foo2();
    }
}

void foo2(){
    //your function
}

If you want to perform some function once the Asynctask is complete, You can also update the UI from within onPostExecute, which is simpler if it works for you.如果您想在 Asynctask 完成后执行某些功能,您还可以从 onPostExecute 中更新 UI,如果它适合您,这会更简单。

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

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