一.启动和停止方式
1,startService() stopService() stopself() stopSelfResult()
此种方式启动的特点:服务启动之后跟启动源无任何关系,无法得到服务对象
2,bindService() unbindService()
启动特点:通过IBinder接口实例,返回一个ServiceConnection对象给启动源,通过ServiceConnection对象的相关方法可以得到service对象
二.生命周期
1,unbounded service :call to startService()-->onCreate()-->onStartCommand()-->Service Running-->(Service is stoped by itself or clients)-->onDestory()-->service shut down
2.Bounded Service:call to bindService()-->onCreate()--onBind()-->Clients are bounded to service-->(All clients unbinded by calling unbindService)-->onUnbind()-- ->onDestory()--->service shut down
三.两种方式启动Service
Myservice1
1,start方式:
Intent intent = new Intent(MainActivity.this,Myservice1.class);
startService(intent);
stopService(intent);
2,bind方式:
bindService(intent,ServiceConnection对象,BIND_AUTO_CARATE);
unbindService(ServiceConnection对象)、
如何得到ServiceConnection对象:
2.1通过Myservice1中onBind()方法返回值IBinder接口实例
(IBinder只是一个接口,不能创建实例,Android中给我们提供的Binder类已经实现了IBinder接口,因此只需要创建内部类MyBinder来继承Binder即可,MyBinder中的方法和参数自定,本例中我们将返回MyService1对象)
class MyBinder extends Binder{
public MyService1 getService(){
return MyService1.this;
}
}
2.2在MyService1中onBind()方法终于派上了用场
public IBinder onBind(Intent intent){
return new MyBinder();
}
2.3在Myserivce1中创建几个模拟方法:play() ,pause(),previous() ,next()
2.4在MainActivity中创建ServiceConnection:
Myservice1 service;
SerivceConnection conn = new ServiceConnection(){
//当启动源跟Service连接意外丢失的时候会调用这个方法,比如Service崩溃了或者被强行停止了
onServiceDisconnected(){};
//当启动源跟Service连接之后会自动调用这个方法
onServiceConnected(组件名,IBinder binder){
//根据biner即为生成的MyBinder对象,之后binder便可以调用MyBinder中的方法获得MyService1实例,也是IBinder接口实例,
service = (Myservice1)binder.getService();
}
};
//之后得到的service便可以调用MyService1中的方法了
之后更改bindService(intent,conn,BIND_AUTO_CREATE)
unbindService(conn);
四.两种启动方式配合使用,可以在没有unbind()的情况下,程序直接退出不会出现错误
startService(intent)
bindService(intent,conn,BIND_AUTO_CREATE);
在MainActivity中的onDestory()方法中:
stopService(intent);
unbindService(conn)
两种启动方式:当服务启动后不需要从启动源获取数据,可以用start启动
服务启动之后,UI不需要了,但仍需要得到回传的数据,可以把两种混合使用