Service startup method
Ordinary startup: write in the corresponding position in Activity
startService(new Intent(getBaseContext(),TestService.class));//启动服务
stopService(new Intent(getBaseContext(),TestService.class));//关闭服务
There are onCreate, onStartCommand, and onDestroy three methods in TestService
oncreate is only called when the service is created, that is, when the service is started for the first time
The onstartCommand method is called every time the service is started, which means that only the onstartCommand method is called when the service is repeatedly started
onDestroy is called when the service is stopped
Binding start:
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 is the same as normal startup, only the first startup call
Binding startup will not call onStartCommand(), but onBind(), and multiple bindings will not call onbind() and onServiceconnected() repeatedly
When the Activity bound to the Service pops out of the stack (that is, finish()), the Service will automatically unbind and stop
So the service life cycle is: onCreate->onStartCommand/onBind->onDestroy