简体   繁体   中英

Android - effective way to manage binding/unbinding from local service across multiple activities

Targeting and building from API Level 4 and above.

Right now, I'm dealing with an issue in which I'm trying to maintain bindings to my local service across multiple activities, and stop the service when the last connection is unbound.

In a nutshell, my service just calls a system service in a HandlerThread that returns quickly to a BroadcastReceiver, then does that same call again after waiting a pre-determined amount of time (at least 15 seconds).

Suppose I have my base activity create the first bond to my service in onCreate() in this fashion:

Intent service = new Intent(ActivityA.this, MyLocalService.class);
getApplicationContext().bindService(service, mConnection, BIND_AUTO_CREATE);

Suppose also that due to the fact that I maintain my binding across screen rotations by carrying over the binder and connection, I do not unbind from the service until the activity is finished: //onRetainNonConfigurationInstance carries over my binder and connection since i bound from the app context, so they are fair game.

public void onDestroy(){
   super.onDestroy();
   //using binder, remove callback to service from current activity
   if(isFinishing(){
      getApplicationContext().unbindService(mConnection);
   }
}

I pretty much do this setup for any other Activity that wants to listen in on the service.

My problem is that eventually, some activities don't unbind instantly, hence the service will still hang around as per the behavior of the bind/unbind pattern if the service is auto created. I had to go as far as stopping my thread before unbinding on the last activity, which prevented any system services being called in the BG. Is there a better way to manage binding and unbinding services, or am I doing my best with my current setup? Also, since my service (via the binder) is weakly referenced, would this reduce my risk of leaking memory?

Apparently, it wasn't un-registering due to the fact that I was not passing the binding across rotations and that I was using an internal state flag to determine whether or not the activity was rotating (was set to true when onRetainNonConfigurationInstance() was called). In most cases, it was not reading the state properly in onDestroy().

I ended up unbinding when isFinishing() resolved to true in onDestroy() as well as passing the bindings through onRetainNonConfigurationInstance(), and as a result, the service was able to shut down on the last unbinding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM