android - android中的service、intentService有什么区别?

标签 android android-asynctask android-service intentservice

Service和Android中的IntentService有什么区别?

AsyncTask和Android中的IntentService有什么区别?

最佳答案

1. Service 和 IntentService 的区别

Service:它是 Android 服务的基类,您可以扩展它来创建任何服务。 由于服务在 UI 线程内运行,因此需要您创建一个工作线程来执行其工作。

IntentService:它是Service的子类,可以简化你的工作。它已经在工作线程中工作,并且可以接收异步请求。因此,您无需手动创建它,也无需担心同步问题。您可以简单地扩展它并覆盖该方法:

onHandleIntent(Intent intent)

您可以在其中管理所有传入的请求。

看看documentation ,您可以详细了解 IntentService 为您做了什么:

  • 创建一个默认工作线程,该线程执行传递给 onStartCommand() 的所有 Intent ,独立于应用程序的主线程。
  • 创建一个工作队列,一次将一个 Intent 传递给您的 onHandleIntent() 实现,因此您无需担心多线程。
  • 在处理完所有启动请求后停止服务,因此您无需调用 stopSelf()
  • 提供返回 null 的 onBind() 的默认实现。
  • 提供 onStartCommand() 的默认实现,将 Intent 发送到工作队列,然后发送到您的 onHandleIntent() 实现。

因此,如果您需要更多控制权,可以使用 Service 类,但通常对于简单的服务,最好的解决方案是 IntentService

<强>2。 AsyncTask 和 Service 的区别

它们是两个不同的概念。

Service: 可以设计为没有界面的 Activity。它适用于长时间运行的操作。

AsyncTask: 是一个封装工作线程(执行后台操作)的特殊类,便于与 UI 线程交互,无需直接管理线程或处理程序。

关于android - android中的service、intentService有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31451476/

相关文章:

Android 推送通知 - Google Play

android - 如何将json数据加载到android中的 fragment 中

安卓服务自动停止

java - Android 使用斑马打印机 imz320 打印阿拉伯语显示为反转字符

android - TextAppearance_Holo_Large - 未找到资源

android - Android 应用程序中的数据绑定(bind)和 RecyclerView

android - 单击按钮时无法取消异步任务

android - Android 中 AsyncTask 内的 JSONException

android - 第 2 部分 由 UI 启动的持久性前台 android 服务,也可以在 sleep 模式下工作,也可以在手机重启时启动

android - 使用 startForeground 的 Android 服务会影响 Play 商店的自动更新吗?