Android – Service – Lifecycle, hook methods and start/stop a service – Part 2

You can read part 1 here.

how to start and stop a service, <span>Android – Service – Lifecycle, hook methods and start/stop a service – Part 2</span>, KandZ

service hook methods

  • onCreate() – The service is being created and this method is launched only one. It is used to initialize the service.
  • onStartCommand() – The service is started because of startService(). This method is called every time intent is sent via startService() – only for started service
  • onBind() – A client is binding to the service via bindService(). All the intent extras are not visible here. – only for bound service
  • onUnbind() – is called when all clients have been disconnected via unBindService(). It returns true to enable new clients to bind to the service later with reBind() – only for bound service
  • onRebind() – it is called when a client is binding to the service via bindService() and after an onUnbind() has been called – only for bound service
  • onDestroy() – it is called when a service shutdown. It is used to clean up resources used by the service.

Launch a service

You can launch a started service with startService(Intent)

Intent intent = new Intent(context, MyService.class);
startService(intent);

If you want to launch a bound service then you should use bindService(Intent, ServiceConnection, Flags)

private ServiceConnection myConnection = new ServiceConnection() {
....
}

Intent intent = new Intent(this, LocalService.class);
bindService(intent, myConnection, Context.BIND_AUTO_CREATE);

There are three flags you can use: BIND_AUTO_CREATE, BIND_DEBUG_UNBIND and BIND_NOT_FOREGROUND. You can read more here.

Stop a service

You can stop a stop a service with stopService(Intent)

Intent intent = new Intent(context, MyService.class);
stopService(intent);

END OF PART 2

94370cookie-checkAndroid – Service – Lifecycle, hook methods and start/stop a service – Part 2Android – Service – Lifecycle, hook methods and start/stop a service – Part 2

Related posts