Service or thread
Service is used to perform long background tasks, and threads can perform background tasks, what are the differences?
1. By default, the service is running in the main thread, and if you are taking a long time to work, you should open another thread in the service to execute.
The priority of the 2.Service is higher than the activity, also higher than the activity of the thread, all in the case of insufficient, not easy to kill the service, even if it is killed, but also when the resources are available to restart the killed service. In fact, thread is just a tool class for performing background work, service and thread are different, we should not discuss their differences, but should discuss where to create thread.
In general, thread can be created in three locations, different locations, different lifecycles, so we should decide whether to create thread in service or activity based on the thread's target life cycle.
1. Create in activity
In this case, when OnCreate is created and destroyed in OnDestroy, the thread is still running in the background after the activity finishes. This situation is suitable for tasks that depend on the activity itself, such as updating the control state of the activity on a regular basis.
2. Create in Application
This will customize the application class, create the thread in the OnCreate method, destroy the thread in the onterminate, or the entire application exits and the thread is running in the background. This situation is suitable for performing some application-level tasks, such as checking the network situation periodically in the background.
In both cases, the thread's life cycle should not exceed the entire application life cycle, and after the app exits, thread should also end so that no memoryleak will appear.
If you want the thread to run after the entire app exits, you should put the thread in the service.
3. Create in service
As long as the service does not exit, thread will not end, typically created in the service's OnCreate, destroyed in OnDestroy.
Ideal for performing some app-independent background tasks, such as maintaining a long connection to the server in the service.
The thread and service of Android