I've got AsyncTask
in my Activity
, when user clicks button, I start an AsyncTask
:
@Override
public void onClick(View view) {
switch(view.getId()){
case R.id.btnLogin:
if(task==null){
task=new LoginTask(this开发者_如何学编程);
task.execute();
}
break;
}
}
But if user clicks button after task is completed, I want it to be executed one more time. What should I do accomplish this? Should I create new task every time user clicks button? Is it OK to create new instance if task is already running? Also, task is static inner class, in order to handle screen rotation.
Declare task as a class variable.And in the postExecute of AsynchTask make it null.Probably you are done
You can execute your AsyncTask's on an Executor
using executeOnExecutor()
Now the pool of threads by default run in parallel :
Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. After HONEYCOMB, it is planned to change this back to a single thread to avoid common application erors
To make sure that the threads are running in a serial fashion please use: SERIAL_EXECUTOR
.
Misc: :How to use an Executor
If you want it to run only if previous instances have already finished, then you can use AsyncTask.getStatus(), to only start a new task if the status is AsyncTask.Status.FINISHED.
Don't run it at the same time. Make a queue of the Asynctasks and run one after the other.
精彩评论