问题
I have several AsyncTask
s doing network operations. I was recently asked to add, after each of these operations, another network call that invokes a remote service sending some statistics. I'd like this statistics call not to delay 'main' network calls, and so I was thinking of executing them in a thread created and started inside the AsyncTask
's doInBackground()
. This thread would most probably end after the doInBackground()
and possibly the whole AsyncTask
has ended. I tried this and it works, but I was wondering if there are side effects, such as memory leaks or similar?
Thanks ;)
回答1:
Try starting a second AsyncTask in the first AsyncTasks 'onPostExecute' Method. For me this worked without any issues.
回答2:
If you want to start thread in doInBackground
method, you can start it in onProgressUpdate()
method
Example:
protected class MyTask extends AsyncTask<Void,Integer,Void> {
public static final int START_THREAD = -1;
@Override
protected void onProgressUpdate(Integer... values) {
if(values[0] == START_THREAD){
startThread();
}
}
@Override
protected Void doInBackground(Void... params) {
publishProgress(START_THREAD);
return null;
}
}
来源:https://stackoverflow.com/questions/7607399/executing-a-thread-inside-asynctasks-doinbackground