📌  相关文章
📜  Android 中的 Service 与 IntentService

📅  最后修改于: 2022-05-13 01:58:10.750000             🧑  作者: Mango

Android 中的 Service 与 IntentService

我们每天都会遇到各种在后台运行的移动应用程序。此外,在许多应用程序中,某些活动是在不使用任何 UI 的情况下执行的,即工作是在后台执行的。例如,我们移动设备上的音乐应用程序或任何其他音乐应用程序在后台运行,您可以在使用音乐应用程序时正确使用任何其他程序。因此,Service 或 IntentService 用于实现此功能。

在本文中,我们将研究 Service 和 IntentService 之间的区别。但是,在我们进一步讨论之前,让我们再次通过 Service 和 IntentService。

差异表

Service

Intent Service

Consider Service to be an Android component that is used to execute various long-running activities in the background, such as in the Music app, where we run the app in the background while using other mobile applications concurrently. The nicest aspect is that no UI is required for the processes to be executed in the background.The IntentService’s base class is the Service. Essentially, it follows the “work queue process” structure, with the IntentService handling client on-demand requests (represented as Intents).
You can also perform some InterProcess Communication (IPC) by using Service. As a result, you can perform a number of operations concurrently with the help of Service because any application component can start a Service and run it in the background.When a client submits a request, the Service is launched, and after handling each and every Intent, the Service is terminated.
The user will never know what is going on in the background of the program in this case.Clients can use Context.startService to make a request to start a Service (Intent). In this case, a worker thread is established, and all requests are handled by the worker thread, but only one request is processed at a time.
When one or more application components bind the Service using the bindService() function, it is referred to as a bound service. If the apps unbind the Service, it will be destroyed.The Service may be activated from any thread, but the IntentService can only be triggered from the main thread, which means that the Intent is received on the Main thread first, and then the Worker thread is run.
As a result, you may conduct a lot of tasks concurrently with the assistance of Service since any application component can start a Service and run it in the background.You will have difficulty interacting with the application’s UI if you use IntentService. If you wish to display certain IntentService results in your UI, you must use an Activity.
To start a Service, use the onStartService() function, but to start an IntentService, use Intent, i.e. start the IntentService by calling Context.startService (Intent).Because Service operates on the Main thread, there is a risk that your Main thread will be stopped if you utilise it. In the case of IntentService, however, the Main thread is not involved. The jobs are completed in the form of a queue, i.e. on a first-come, first-served basis.

结论

在本文中,我们了解了 Android 的 Service 和 IntentService 之间的区别。我们谈到了启动和终止服务和 IntentService 的许多方法中的一些。如果您只需要在后台完成一些活动,您可以使用Service;否则,您可以使用 IntentService。