Android: AsyncTask, my 1st task has not finished when the other starts

元气小坏坏 提交于 2019-12-24 13:23:23

问题


Here's my code in my main thread

            myAsyncRunnable mar = new myAsyncRunnable(GameActivity.this);
            mar.execute("fire");
            PhotoTask photoTask = new PhotoTask(camera,surfaceCamera,isPreview,holder,GameActivity.this);
            photoTask.execute(null);

in myAsyncRunnable.fire() I have a loop that changes 10 times the image of an ImageView in gameActivity. I want the photoTask to start when the last image has been changed

@Override
protected Void doInBackground(String... params) {
fire();
return null;
}

public void fire() {
        final ImageView image3 = (ImageView) gameactivity.findViewById(R.id.imageView3);
        final int drawables[] = new int[] {R.drawable.fire1,R.drawable.fire2,R.drawable.fire3,R.drawable.fire4,R.drawable.fire5,R.drawable.fire6,R.drawable.fire7,R.drawable.fire8,R.drawable.fire9,R.drawable.fire10,R.drawable.fire11,R.drawable.fire12,R.drawable.fire13,R.drawable.fire14,R.drawable.fire15,R.drawable.fire16};
        for (int i=0;i<drawables.length;i++) {
            final int j=i;
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    image3.setImageResource(drawables[j]);
                }
            };
            gameactivity.handler.postDelayed(runnable, 200*j);
        }
    }

But photoTask executes before the last image has apperaed. This is probably due to the postDelayed method and I have tried to execute photoTask in the method onPostExecute() but it didn't work either


回答1:


Put photoTask.execute(null); in the onPostExecute() of the first AsyncTask




回答2:


Just as pvn said, you need to override the onPostExecute method too and execute your photo async class there. Put this after the doInBackground method.

@Override
protected void onPostExecute(YourParam param)
{
     PhotoTask photoTask = new PhotoTask(camera,surfaceCamera,isPreview,holder,GameActivity.this);
        photoTask.execute(null);
}


来源:https://stackoverflow.com/questions/14811810/android-asynctask-my-1st-task-has-not-finished-when-the-other-starts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!