Service需要了解的理论知识

Service概念:能在后台长时间运行,且不提供用户界面的应用程序组件。

1.Service分类:

Started Service:当应用程序组件(如activity)通过startedService()方法启动Service时,Service处于启动状态,一旦启动,service 就可以在后台无期限运行;停止自身需要调用stopSelf()方法或者其他组件调用stopService()方法来止Service,Service 停止 时,系统将其销毁;

Bound Service:当应用程序组件通过调用bindService()方法绑定到service时,service被创建处于绑定状态,客户端通过IBinder接 口与Service通信,多个组件可以绑定到一个service上,当他们都解绑时,service被销毁;

Intent Service:是继承于service并处理异步请求的一个类,会创建独立的worker线程来处理所有的intent请求,无需处理多线程问 题,所有请求完成后IntentService会自动停止,无需调用stopSelf()方法停止service;使用时继承IntentService类,重写 onHandlerIntent()方法即可,在不必同时处理多个请求时,是最佳选择;

 2.Service生命周期:
start Service:

onCreate()--onStaetCommand()--stopService()/stopSelf()--onDestroy();

bindService():

onCreate()--onBind()--unBindService()--onUnbind()--onDestroy;

 3.在创建service后,系统在AndroidManifest.xml文件中自动配置Service,使 用<service.../>标记,会出现enabled、exported两个属性

android:enabled

能否被实例化,true表示能,false表示不能,默认为true;

android:exported

其他组件是否可以调用Service或者与其交互,true表示能,false表示不 能;

 4.使用Service需注意的问题:

Service不会专门启动一个线程执行耗时操作,所有的操作都在主线程中进行, 所以容易出现ANR(程序无响应,可选择等待或 关闭)情况;

Service不会自动停止,需要调用stopSelf()或者stopService()方法停止;

 5.IntentService

使用IntentService不会出现4中的问题,因为IntentService在开启Service时, 会自动开启一个新的线程去执行,请求完成 后IntentService会自动停止;

猜你喜欢

转载自blog.csdn.net/wuqingsen1/article/details/78803596