问题
I had read quite a number of resources regarding the Service
and IntentService
. However when come to make a decision, I am not confident enough to choose which type to use in order to create a background service that will poll data from database in a time interval and stop it when I get the data I want since the data represent a status of a request, eg. ordering medicine confirmation status(pending, completed, in progress). I need to detect when a status is set to "completed" and send a notification to alert the user that the order is completed. After that the service will stop itself automatically.
Please kindly advice. Thank you.
回答1:
Intent Service -
Works in Worker Thread , not in Main Thread.
Intended to execute their action is separate thread and then get shut down.
They do perform their operation and stops.
Ideal to perfrom things like htp get ,don't require to stay connected with server.
Service -
Runs in main thread.
Ideal when there is requirement to stay connected with server (i.e. permanent tcp connection), the way you can go is to have a service (not an intent one) that performs the networking stuff using an asynctask or a more classic thread hosted in the service
回答2:
It makes no difference. Use whatever you find easier. This question isn't worth spending any time worrying about. Just make sure you understand what code needs to run on the main (UI) thread and what code needs to run on a background (worker) thread. In IntentService
the "long-running operation" needs to run in onHandleIntent()
If you are using Service
in onStartCommand()
you would start your own background thread and execute the "long-running operation" on that.
来源:https://stackoverflow.com/questions/14450804/service-and-intentservice-which-is-better-to-run-a-service-that-poll-database-v