Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Services: Bind on demand vs. Bind on #onCreate()

We have a Service that takes care of several things in one of our activities. We are fairly new to Android and wondering what the perfect moment for binding to that service is. We only need the service for half of the interactions that are possible via the activity. So we have to settle for one of two possibilities:

  • bind to the Service when we really need it, which would add a fair amount of overhead implementation-wise
  • bind to the Service in the onCreate() method without the overhead of checking if the service is running, binding it on demand, maybe caching requests made etc.

What would be the "android way" here? Is a running service a lot of overhead or should it only be started when really needed? The service itself is really lightweight.

like image 501
Andreas Mohrhard Avatar asked Nov 14 '22 10:11

Andreas Mohrhard


1 Answers

Personally I prefer to call bindService() in onCreate(), and after finish using it call unbindService() in onDestroy(). Reason for that is bindService() is actually an asynchronous call. which has not been well-documented in the API. When you call bindService(), the reference of binder object you get inside ServiceConnection.onServiceConnected() callback method is not get instantiated immediately, there is a lag in the meantime after calling bindService() and before binder object get instantiated and ready to use. so the most suitable place to call it is onCreate() as we usually do not preform much heavy operations and need use binder object immediately at this stage.

like image 162
yorkw Avatar answered Nov 16 '22 04:11

yorkw