开发者

How can I call a statement after two asyncTask calls in Android?

开发者 https://www.devze.com 2023-04-04 18:27 出处:网络
I have a method like: void doStuffs() { new asyncCall1().execute(); new asyncCall2().execute(); } How can I call another method after the two 开发者_开发百科async calls have ended?Use the get metho

I have a method like:

void doStuffs() {
    new asyncCall1().execute();
    new asyncCall2().execute();
}

How can I call another method after the two 开发者_开发百科async calls have ended?


Use the get method to wait for the work to complete in a third async task:

    (new AsyncTask<Void, Void, Void>() {

        @Override
        protected Void doInBackground(Void... params) {

            asyncCall1.execute((Void)null);
            asyncCall2.execute((Void)null);

            try {
                asyncCall1.get();
                asyncCall2.get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }

            return (Void)null;
        }

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



    }).execute((Void)null);


You need to invoke the method from the AsyncTask. The easiest way would be to wrap the statement in a public static method within your activity. Otherwise, you can pass the AsyncTask a reference to the activity. The classiest way to do it would be to use a Handler

Either way, your AsyncTask should go

@Override
onPostExecute(Result r)
{
    //logic goes here
}


Maybe pass a Handler in to both the AsyncTasks which get called onPostExecute and build logic in to the handler :

Handler asyncTaskHandler = new Handler() {
    private boolean firstTaskComplete = false;
    @Override
    public void handleMessage(Message msg) {
        synchronized (firstTaskComplete ) {
            if(!firstTaskComplete) {
                firstTaskComplete = true;
            } else {
                // call some other code
            }
        }
    }
};
0

精彩评论

暂无评论...
验证码 换一张
取 消