Android 在另一个完成后立即调用 AsyncTask [英] Android calling AsyncTask right after an another finished

查看:25
本文介绍了Android 在另一个完成后立即调用 AsyncTask的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 Android AsyncTask 时遇到了一些问题.有一个 Activity 包含一些 TextView 一个按钮和一张图片.当用户进入此活动时,我启动一个异步任务来检查用户是否可以从该活动开始(直到任务未完成按钮未激活).然后我想启动另一个异步任务来获取图片.所以我做了一个内部类:

I have some problem with Android AsyncTask. There is an Activity which contains some TextView a button and a picture. When an user entered this activity I start an asynctask to check whether the user can go toward from the activity (until the task not finish the button not active). Then I want to start another asyntask to get the picture. So I made an inner class:

AsyncTask<String, Void, JSONObject>() authTask = new AsyncTask<String, Void, JSONObject>() {
     @Override
     protected JSONObject doInBackground(String... params) {
         //call the rest api
     }
     @Override
     protected void onPostExecute(JSONObject result) {
         // check the result
         // and make another asynctask
         AsyncTask<String, Void, Bitmap> imageTask = new Async.... {
             // get image
         }
         imageTask.execute();
     }
}

然后我打电话authTask.execute(); 来自 UI 线程.

and I call authTask.execute(); from the UI thread.

我对此有一种不好的感觉,尤其是它似乎不起作用(几次没问题,但突然它冻结"了:也不例外,只是挂起并且进度条在旋转.什么也没有发生,按钮也不会积极的.)还有另一种获取信息的方法,当它完成后立即开始另一个任务?

I have a bad feeling about this, especially it seems doesn't work (it's ok few times but suddenly it "freeze": no exception just hanging and the progress bar is spinning. Nothing happens and the button won't be active.) There is another way to get an information and when it's finished immediately start another task?

UDPATE:我使用 api 级别 10.在 authTask 中,我获得了一些启动 imageTask(某些 ID)所需的信息,因此我必须连续调用这些任务.在 api 级别 10 中这是可能的吗?

UDPATE: I working with api level 10. In authTask I get some information which is needed to start imageTask (some id) so I have to call these tasks in a row. In api level 10 it's is possible?

提前致谢!

兄弟,彼得

推荐答案

您可以使用 getStatus() 检查 AsyncTask 是挂起、正在运行还是已完成.当 finsh 开始你的新任务时.比如:

you can use getStatus() checks whether the the AsyncTask is pending, running, or finished.and when finsh start your new task.like:

if(authTask .getStatus() == AsyncTask.Status.PENDING){
    // My AsyncTask has not started yet
}

if(authTask .getStatus() == AsyncTask.Status.RUNNING){
    // My AsyncTask is currently doing work in doInBackground()
}

if(authTask .getStatus() == AsyncTask.Status.FINISHED){
    // START NEW TASK HERE
}

您的应用示例:

btn.setOnClickListener(new View.OnClickListener()
  {
    public void onClick(View v)
      {
        if (authTask != null && authTask.getStatus() == AsyncTask.Status.FINISHED) {
           //START YOUR NEW TASK HERE
        }
        else
        {
          //IGNORE BUTTON CLICK
        }
      }
   }); 

这篇关于Android 在另一个完成后立即调用 AsyncTask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆