4

我在另一个线程中有一些工作要做(通过doingAsyncTask)。当用户单击按钮时工作开始。但同时只有一个doingAsyncTask对象必须做这个工作,如果doingAsyncTask正在工作,那么点击按钮不能创建doingAsyncTask的新对象并执行它,它必须等到工作完成。我怎样才能检查它?

public class SearchActivity extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //....
    }

    public void onclickButton(View view) {
        new doingAsyncTask().execute();
    }

    public class doingAsyncTask extends AsyncTask<Void, Void, Void> {
    protected Void doInBackground(Void... unused) {
        //doing something
        return(null);
    }

    protected void onProgressUpdate() {
    }
    protected void onPreExecute() {
    }
    protected void onPostExecute() {
    }
   }
}

解决 了所有问题,它对我有用

      if(task.getStatus() == AsyncTask.Status.FINISHED)
            task=new ProgressBarShow();
        if(task.getStatus() == AsyncTask.Status.PENDING){
            //task=new ProgressBarShow();
            task.execute();
        }
4

4 回答 4

9

检查此AsyncTask.Status

AsyncTask.Status    FINISHED    Indicates that onPostExecute(Result) has finished. 
AsyncTask.Status    PENDING     Indicates that the task has not been executed yet. 
AsyncTask.Status    RUNNING     Indicates that the task is running. 

代码:

if (doingAsyncTask().getStatus().equals(AsyncTask.Status.FINISHED))
     doingAsyncTask().execute();
else

编辑:

public class SearchActivity extends Activity {
    doingAsyncTask asyncTask; 

    public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);             
       // ...
       asyncTask = new doingAsyncTask();   
    }
    public void onclickButton(View view) {
         if(ayncTask.getStatus().equals(AsyncTask.Status.FINISHED) || ayncTask.getStatus().equals(AsyncTask.Status.PENDING)) {
             asyncTask.execute();
         }
         else {
             // do something
         }
    }
    // ...
}
于 2012-04-06T11:42:08.360 回答
2

您可以检查 AsyncTask => AsyncTask.Status的状态

例如:

    myAsyncTask mtask = new myAsyncTask();
    mtask.execute();

   // write this wherever you want to check status
   if(mtask.getStatus() == AsyncTask.Status.FINISHED){
        // My AsyncTask is done and onPostExecute was called
    }
于 2012-04-06T11:42:06.470 回答
0

在设置新任务之前使用AsyncTask 的getStatus()检查其状态

于 2012-04-06T11:43:20.787 回答
0

代码可能是这样的:

doingAsyncTask task;
public void onclickButton(View view) {
    if(task==null){
        task=new doingAsyncTask();
        task.execute();
    }
    else if(task.Status!=RUNNING){
        task=new doingAsyncTask();
        task.execute();
    }
}
于 2012-04-06T11:53:05.687 回答