Run asynchronous task with onhandleintent

Should we run the asynchronous task from the onHandleIntent() the IntentService method? I read that onHandleIntent() works in worker thread , so it will be safe to run asyncTask from there?

+4
source share
3 answers

IntentService are already background processes; there is no need to run AsyncTask. In addition, starting AsyncTask is โ€œsafeโ€ from anywhere; this is a helper class that helps you multithreaded. Just make sure that you are not manipulating the View in the doInBackground() method of your AsyncTask if you use it in your activity.

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

new theme (Runnable r) .start ();

See the example in How to run a Runnable thread in Android?

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

+3
source

The AsyncTask class is used to provide a mechanism for achieving multithreading, so the event flow will not hang, but since you are using the service, you should not use AsyncTask in the service, instead you can use threads if some long-running task is to be performed in the Service.

0
source

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

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

In my case, I did this because the entire application request was made by a class that extended AsyncTask, and because of the implementation, it was difficult to reorganize the code.

0
source

Source: https://habr.com/ru/post/1447443/


All Articles