Service
能够在后台长时间运行,并且没有用户界面的应用程序组件。
Service按启动方式可以分为Started Service和Bound Service。
Started Service:调用startService()方法来启动的Service,通过这个方法运行应用的时候服务并没有启动,当应用程序组件调用这个startService()方法时才启动。
Bound Service:调用bindService()方法来启动,当应用运行的时候这个Service和Activity就绑定到一起了,当Activity停止,Service也会相应停止。
Service的基本用法:
在Android Studio中可以直接新建一个Service,在这个类中,重写onBind()、onCreate()、onStartCommand()、onDestroy()方法。onCreate()方法在创建时应用,onStartCommand()方法在每次启动Service时调用,onDestroy()在Service销毁的时候调用。
在创建了这个Service后Android Studio会自动在AndroidManifest.xml中配置这个Service通过Service标签,其中enabled属性是指这个Service能否被实例化,exported属性是指其他应用程序是否可以调用这个Service或与之交互。
//启动Service首先需要一个Intent对象,并实例化这个Intent对象
Intent intent = new Intent(MainActivity.this,创建的Service.class);
//启动Service
startService(intent);
停止Service:可以通过Service自身调用stopSelf()方法,或者其他的组件调用stopService()方法。
//停止Service同样需要Intent对象
Intent intent = new Intent(MainActivity.this,创建的Service.class);
//停止Service
stopService(intent);
Service的生命周期:调用StartService()方法以后,会首先调用onCreate()方法,接着调用onStartCommand()方法,这时Service处于运行状态,如果调用stopSelf()或stopService()方法则Service处于停止状态,这时onDestroy()方法被调用,Serevice处于销毁状态。
BoundService:
如果Service和启动他的组件需要进行方法调用或者交换数据就需要使用BoundService。
BoundService的生命周期:调用bindService()方法以后,会首先调用onCreate()方法,接着调用onBind()方法,这时客户端组件就绑定到了Service,如果调用unbindService()方法就会解除绑定,之后会调用onUnbind()和onDestroy()方法,这时Service被关闭。
实现BoundService的步骤:
先创建Service并重写onBind()方法,在Service中创建一个继承自Binder类的内部类,然后修改onBind()方法,让其返回一个IBinder对象(IBinder对象用来和绑定他的组件进行通信的)。在客户端即Activity,首先创建一个ServiceConnection对象,用来获取onBind()方法返回的IBinder对象,然后在onStart()方法中调用bindService()方法来绑定Service,在onStop()方法中调用unbindService()方法来解除绑定。
IntentService:
IntentService是Service子类。普通的Service不能自动开启线程,也不能够自动停止服务,而IntentService可以。
例如在Service中编写一个耗时任务的代码,需要手动开启一个线程来实现这个耗时任务,否则在执行后会出现ANR(应用无响应)错误,如果在IntentService中即可不创建线程。
创建一个Java类让其继承自IntentService,添加构造方法并实现onHandleIntent()方法。将具体的需要线程的操作写到onHandleIntent()方法中。