Heavy calculation on background thread
Im developing an application in Android that receives real-time data (via BT) and needs to process it and show it in a graph. The processing part is quite heavy so I want to do it in background. I've been reading about my possible options:
New Service with a separate thread -> I don't need to have a different lifecycle (processing will be finished as soon as the application closes).
Runnable in a new thread -> I can only invoke the start method once (and i will need to run the processing every 4 seconds or so..)
AsyncTask -> Same problem as before, i can only call "execute" once.
What is my best option? Is it viable (in terms of memory and performance开发者_如何学编程) to create a new AsyncTask (or a new Theread) everytime I want to process the data (every 3 or 4 seconds..)?
Thank you
AsyncTask uses thread pool. So if you execute new AsyncTask second time, old thread is used. So you dont have to worry about starting new threads.
You can use IntentService. Commands to IntentService are enqueued and executed from one worker thread. In result only one command is executed at time.
you should use thread in service with infinite loop and when your app exits, you can maintain a boolean which will help you in stopping the service and freeing the resources from thread..
Don't forget to free the resource from the service as android does not do this for you....
Difficult to be more accurate without knowing the whole data lifecycle, but I would say yes, it is perfectly workable to run a new Thread
every 3 or 4 seconds.
To redesign your Thread
in a way it allows the caller to feed it with a new bunch of data every 3 or 4 seconds would probably be even better. This way this Thread
would remain unique and reusable all the time your application is running.
The best option is AsyncTask class because all Application runs on single thread i.e user interface thread and your application consist of heavy processing and user is not concern with the processing part, user is concern with the output i.e graph so with the help of AsyncTask you perform the processing part of application in background. And for time interval you can apply thread concept in AsyncTask too.
精彩评论