Search code examples
androidandroid-serviceandroid-service-binding

Is it relevant to keep a mBound flag when binding a service?


As explained in the documentation regarding bound services, a mBound boolean is used to know whether a service was bound in an activity. Here is an excerpt of the code example given in the documentation:

public class BindingActivity extends Activity {
  LocalService mService;
  boolean mBound = false;

  private ServiceConnection mConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder service) {
      LocalBinder binder = (LocalBinder) service;
      mService = binder.getService();
      mBound = true;
    }
}

Why use an additional member rather than setting mService to null if it is not bound? It seems redundant to me, and potentially error-prone.


Solution

  • There is no need to keep an additional flag in your Activity.

    Additional flag adds risk on data consistency and atomicity, such as:

    • data consistency: Someone else modify this code may be confused on should mBound or mService != null be used, just as you're. They may worry about this and add assert(mBound == mService != null); check.

    • atomicity: In strict thread safe conditions, onServiceConnected may just be blocked before mBound = true;, while in other thread, mService and mBound may conflict in state.

    • complexity: What if someone else editing the code just modified mBound to other state by mistake?

    Hope this could help.