With activity, why do you need a service?

Service is a mechanism android, and when it runs if it is Local Service, then the corresponding Service is running on the main thread of the main process. Such as: onCreate, onStart these functions are running on the main thread in the main process is invoked system. If Remote Service, then the corresponding Service is running in the main thread is independent of the process. So do not understand the Service as a thread, the thread it with half dime had nothing to do!

  If so, then why do we use the Service it? In fact, this mechanism with the android system related, we acquire Thread it. Thread is run independent of Activity, which means that when an Activity after being finish, if you do not take the initiative to stop Thread or Thread in the run method has not been completed, then, Thread also been implemented. So there will be a problem: when the Activity is finish, you no longer hold the Thread of reference. On the other hand, you have no way to control the same in a different Thread Activity in.
  
  For example: If you need to keep the Thread will connect to the server from time to time to do some kind of synchronization, then the Thread Activity no need to start time is also running. This time when you start an Activity is no way before the Activity which controls the creation of Thread. So you will need to create and start a Service, which is created in the Service, and to control the operation of Thread, this will solve the problem (because any Activity can be controlled by the same Service, and the system will only create an instance of the corresponding Service).
  
  So you can imagine the Service as a messaging service, and you can call Context.startService, Context.stopService, Context.bindService, Context.unbindService wherever Context, and to control it, you can also register BroadcastReceiver in Service, the in other places to control it by sending a broadcast, of course, these are Thread impossible.

Published 41 original articles · won praise 8 · views 20000 +

Guess you like

Origin blog.csdn.net/huma8848888/article/details/84109511