start async task from onhandleintent

跟風遠走 提交于 2019-12-17 20:50:05

问题


Should we start async task from within onHandleIntent() method of IntentService? I read that onHandleIntent() runs in worker thread so will it be safe to start asyncTask from there??


回答1:


IntentServices already are background-processes; there's no need to start an AsyncTask from there. Also, starting an AsyncTask is 'safe' from anywhere; it's a helper class that helps you multithread. Just make sure you don't manipulate Views in the doInBackground()-method of your AsyncTask if you use it in your Activity.

If you need to spawn multiple threads inside your IntentService, just use:

new Thread(Runnable r).start();

See an example at How to run a Runnable thread in Android?

If you need to call some kind of callback, use Handler. For an example, see http://www.vogella.com/articles/AndroidPerformance/article.html#handler




回答2:


AsyncTask class is used to provide a mechanism to do achieve multithreading, so your event thread wont get hanged, but as you are using service, you should not use, AsyncTask in the Service, instead you can use, threads, if some long running task is to executed, in the Service.




回答3:


If you really need to use a AsyncTask inside an IntentService, you can create a method in your AsyncTask that calls de doInBackGround and the onPostExecute. Something like this:

void executeFlowOnBackground(Params params) {
  onPostExecute(doInBackground(params));
}

In my case I did this because all App request were made by a class that extended the AsyncTask, and because of the implementation was difficulty to refactor the code.



来源:https://stackoverflow.com/questions/13491049/start-async-task-from-onhandleintent

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