Difference between service and thread
In many cases, you may ask why we need to use a service instead of a thread, because it is convenient to use a thread, which is much more convenient than a service. I will explain it in detail below.
1). Thread:Thread isProgramThe minimum execution unit, which is the basic unit for CPU allocation. You can use thread to perform some asynchronous operations.
2). Service:A service is a mechanism of Android. If it is a local service during running, the corresponding service runs on the main thread of the main process. For example, oncreate and onstart functions run on the main thread of the main process when called by the system. For remote service, the corresponding service runs on the main thread of the independent process.Therefore, do not set the service
It is understood as a thread, and it has no relation to the thread with half a cent of money!
In this case, why should we use the service? In fact, this is related to the Android system mechanism. Let's talk about thread first. The running of thread is independent from the activity. That is to say, after an activity is finished, if you do not stop the thread actively or the run method in the thread is not completed, the thread will continue to be executed. Therefore, a problem occurs: after the activity is finished, you no longer hold the reference of this thread. On the other hand, you cannot
The activity controls the same thread.
For example, if your thread needs to connect to the server for some synchronization after a period of time, the thread needs to run when the activity does not start. At this time, when you start an activity, you cannot control the previously created thread in the activity. Therefore, you need to create and start a service, create, run, and control the thread in the service to solve this problem (because any activity can control the same service, the system will only create a corresponding
Service instance ).
you can think of a service as a message service, you can call context in any place with context. startservice, context. stopservice, context. bindservice, context. unbindservice, to control it. You can also register broadcastreceiver in the service and control it by sending broadcast elsewhere. Of course, none of these can be done by thread.