Search code examples
androidandroid-serviceandroid-binder

Android local binding


Why do we use getService method here?

public class LocalBinder extends Binder {
    LocalService getService() {
        return LocalService.this;
    }
}

Solution

    • The BoundService acts as a server in a client-server architecture.(You'd probably know this part).
    • A server always exports some service to a client. That service may be a public method.(Like "public void reverse(String)").
    • The getService() function is used to return an instance of LocalService so that Clients can access the public methods of that BoundService though that instance.

    Below is a sample program from the official Android Documentation

    public class LocalService extends Service {
        // Binder given to clients
        private final IBinder mBinder = new LocalBinder();
        // Random number generator
        private final Random mGenerator = new Random();
    
        /**
         * Class used for the client Binder.  Because we know this service always
         * runs in the same process as its clients, we don't need to deal with IPC.
         */
        public class LocalBinder extends Binder {
            LocalService getService() {
                // Return this instance of LocalService so clients can call public methods
                return LocalService.this;
            }
        }
    
        @Override
        public IBinder onBind(Intent intent) {
            return mBinder;
        }
    
        /** method for clients */
        public int getRandomNumber() {
          return mGenerator.nextInt(100);
        }
    }
    

    .

    public class BindingActivity extends Activity {
        LocalService mService;
        boolean mBound = false;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
        }
    
        @Override
        protected void onStart() {
            super.onStart();
            // Bind to LocalService
            Intent intent = new Intent(this, LocalService.class);
            bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
        }
    
        @Override
        protected void onStop() {
            super.onStop();
            // Unbind from the service
            if (mBound) {
                unbindService(mConnection);
                mBound = false;
            }
        }
    
        /** Called when a button is clicked (the button in the layout file attaches to
          * this method with the android:onClick attribute) */
        public void onButtonClick(View v) {
            if (mBound) {
                // Call a method from the LocalService.
                // However, if this call were something that might hang, then this request should
                // occur in a separate thread to avoid slowing down the activity performance.
                int num = mService.getRandomNumber();
                Toast.makeText(this, "number: " + num, Toast.LENGTH_SHORT).show();
            }
        }
    
        /** Defines callbacks for service binding, passed to bindService() */
        private ServiceConnection mConnection = new ServiceConnection() {
    
            @Override
            public void onServiceConnected(ComponentName className,
                    IBinder service) {
                // We've bound to LocalService, cast the IBinder and get LocalService instance
                LocalBinder binder = (LocalBinder) service;
                mService = binder.getService();
                mBound = true;
            }
    
            @Override
            public void onServiceDisconnected(ComponentName arg0) {
                mBound = false;
            }
        };
    }
    

    Let's look more closer.

    The server part.

    public class LocalService is the service that exports(or gives) some functionality to client activities or services.The client imports(or uses) the funtcionality.

    public int getRandomNumber() { return mGenerator.nextInt(100); }

    Above code is the actual functionality or service exported by the server.

    The client part.

    LocalBinder binder = (LocalBinder) service; mService = binder.getService(); mBound = true;

    Here the binder.getService() is used to get the running ( or current) instance (or object) of the LocalBinder class.

    Then,

    int num = mService.getRandomNumber(); Toast.makeText(this, "number: " +num,Toast.LENGTH_SHORT).show();

    mService.getRandomNumber() is used to access the public method.