Executing a thread inside AsyncTask's doInBackground()

断了今生、忘了曾经 提交于 2020-01-04 02:57:11

问题


I have several AsyncTasks 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

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