Service作为四大组件之一,也有其生命周期,在前面的实例中我们使用到了onCreate(),onStartCommand(),onBind(),及onDestroy()等方法,这些方法并不是全部都会进行回调执行,一般的有以下两种情况:
1.在项目的某位置调用了startService()方法,相应的服务的onCreate()就会启动执行,接着回调onStartCommand()方法,直到服务执行完毕调用stopService()方法,回调onDestroy()方法,服务才停止
2.在项目的某位置调用了bindService()方法,相应服务的onBind()方法会被回调执行,如果该服务没被创建过,onCreate()方法也会被执行,执行onBind()后调用方会获取IBinder对象的实例,这样服务和活动之间就可以保持通信了。
前面的应用实例一和二对第一种情况有了很好的说明,下面的应用实例三主要是实现第二种情况的例子:
1.创建mainActivity
public class MainActivity extends Activity implements OnClickListener{
Button bindService;
Button unBindService;
MyService.DownLoadBinder mBinder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bindService = (Button)findViewById(R.id.BindService);
unBindService = (Button)findViewById(R.id.unBindService);
bindService.setOnClickListener(this);
unBindService.setOnClickListener(this);
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
//点击bindservice按钮后,创建intent对象,执行bindService()方法,传入第一个参数为可启动MyService的意图
//传入的第二个参数为创建的和服务建立连接通讯的serviceConnection对象connection
//传入的第三个参数为一个标志位,表示自动创建服务
//点击unbindservice按钮后,调用unbindservice()方法停止通讯连接,即可停止服务
switch (arg0.getId()) {
case R.id.BindService:
Intent intent = new Intent(this, MyService.class);
bindService(intent,connection,BIND_AUTO_CREATE);
break;
case R.id.unBindService:
unbindService(connection);
default:
break;
}
}
//创建和服务建立通讯连接的匿名serviceconnection对象
ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
}
//当创建和服务的通讯连接后,回调函数onBind返回mBinder后,启动onserviceconnection方法,通过mBinder自用启动调用服务中的方法
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
mBinder = (MyService.DownLoadBinder)service;
mBinder.startDownLoad();
mBinder.getProgress();
}
};
}
二.创建MyService
public class MyService extends Service {
DownLoadBinder mBinder= new DownLoadBinder();
public MyService() {
}
//在 使用方法bindService()的时候,调用onBind之前会先调用onCreate()方法
public void onCreate(){
super.onCreate();
Log.d("MyService","onCreate executed");
}
//创建DownloadBinder类继承Binder类,当执行完onBind后调用方获取mBinder实例,
//该实例对象可自由调用该类中的Startdownload或者getProgress等方法
class DownLoadBinder extends Binder{
public void startDownLoad(){
Log.d("MyService", "startDownload execuuted");
}
public void getProgress(){
Log.d("MyService", "getProgress executed");
}
}
@Override
//开始bindService()方法后,回调onBind,获取的mBinder返回调用方,此后调用方可通过mBinder对服务进行随时的指令通讯
public IBinder onBind(Intent intent) {
return mBinder;
// TODO: Return the communication channel to the service.
}
//启动unbindservice()方法后回调onDestroy()方法,停止服务
public void onDestroy(){
super.onDestroy();
Log.d("MyService", "onDestroy executed");
}
}
三.在manifest中对服务进行注册
<service
android:name=".MyService"
android:enabled="true"
android:exported="true" >
</service>
运行程序,打印的log结果如下: