简体   繁体   中英

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() . How can I override onPostExecute() in this case?

不能直接实现,可以通过扩展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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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