Service启动方式
普通启动:在Activity中对应位置写入
startService(new Intent(getBaseContext(),TestService.class));//启动服务
stopService(new Intent(getBaseContext(),TestService.class));//关闭服务
在TestService中有onCreate、onStartCommand、onDestroy三个方法
oncreate只在服务创建时调用,也就是第一次启动服务时调用
onstartCommand方法在每次启动服务时都调用,也就是说重复启动服务时只调用onstartCommand方法
onDestroy在服务停止时调用
绑定启动:
ServiceConnection serviceConnection=new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.d("test", "onServiceConnected: ");
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.d("test", "onServiceDisconnected: ");
}
};
bindService(new Intent(this,AutoRefreshService.class),serviceConnection,BIND_AUTO_CREATE);
onCreate与普通启动一样,只第一次启动调用
绑定启动不会调用onStartCommand(),而是调用onBind(),且多次绑定不会重复调用onbind()和onServiceconnected()
当与Service绑定的Activity出栈时(即finish())Service会自动解绑并停止
所以Service的生命周期为:onCreate->onStartCommand/onBind->onDestroy