通过前面的学习,大家会发现我们在使用 Service 时总会创建一个线程来执行任务,而不是直接在 Service中执行。这是因为 Service 中的程序仍然运行于主线程中,当执行一项耗时操作时,不新建一个线程的话很容易导致 Application Not Responding 错误。当需要与 UI线程进行交互时,使用 Handler 机制来进行处理。
为了简化操作,Android提供了IntentService类。IntentService是 Android中提供的后台服务类,是Service 自动实现多线程的子类。IntentService 在 onCreate(函数中通过 HandlerThread 单独开启一个线程来处理所有Intent 请求对象所对应的任务,这样以免请求处理阻塞主线程。执行完一个 Intent 请求对象所对应的工作之后,如果没有新的 Intent 请求到达,就自动停止Service;否则执行下一个Intent 请求所对应的任务,直至最后执行完队列的所有命令,服务也随即停止并被销毁。所以如果使用 IntentService,用户并不需要主动使用 stopService()或者在lntentService 中使用 stopSelf()来停止。
lntentService在处理请求时采用的也是 Handler机制,它通过创建一个名叫 ServiceHandler 的内部 Handler 直接绑定到 HandlerThread所对应的子线程。ServiceHandler 把处理一个 intent 所对应的请求都封装到 onHandleIntent()方法中,在开发时只需要直接重写 onHandleIntent()方法,当开启服务之后系统会自动调用此