简体   繁体   English

如何在Android中的AsyncTask中执行AsyncTask

[英]How to do AsyncTask inside AsyncTask in Android

I want to start an AsyncTask inside another AsyncTask. 我想在另一个AsyncTask中启动一个AsyncTask。 I'm trying to do this by starting the second AsyncTask in 'onPostExecute' of the first AsyncTask. 我试图通过在第一个AsyncTask的'onPostExecute'中启动第二个AsyncTask来做到这一点。 The result is that the second AsyncTask starts after the first has finished. 结果是第二个AsyncTask在第一个完成后启动。 How can I solve this? 我该如何解决?

Thank you 谢谢

here's the code 这是代码

private class Parse extends AsyncTask<Void, Void, Void>{
    Document doc = null;
    Element son = null;

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

    @Override
    protected Void doInBackground(Void... params) {
        try {
            doc = Jsoup.connect("MY_URL").get();
            son= doc.body();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);

        for(CONDITION){
            //MY_CODE

            new DownloadImageTask().execute();

        }
    }
}

This is the second AsyncTask 这是第二个AsyncTask

private class DownloadImageTask extends AsyncTask<String, Void, String> {

    Bitmap bitmap;
    ImageView image = new ImageView(Events.this);

    @Override
    protected void onPreExecute() {
    };

    protected String doInBackground(String... urls) {
    try {
        URL url = new URL("MY_URL");
        bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
        return null;
}

First, please refer to the oficial documentation to have a best understanding about AsyncTask: http://developer.android.com/reference/android/os/AsyncTask.html 首先,请参阅官方文档以对AsyncTask有所了解: http : //developer.android.com/reference/android/os/AsyncTask.html

The onPostExecute runs in the main thread, after the background task finishes. 后台任务完成后,onPostExecute在主线程中运行。 This method is designed this way to be used to comunicate with the UI thread to handle the execution. 此方法是通过这种方式设计的,用于与UI线程通讯以处理执行。

If you want to run the second AsyncTask with your background code, or just after it started, you have to do this on the doInBackground method. 如果要使用后台代码运行第二个AsyncTask,或者要在它刚启动后运行它,则必须在doInBackground方法上执行此操作。

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

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