Creating Bound Service with help of Binder

suggest change

Create a class which extends Service class and in overridden method onBind return your local binder instance:

public class LocalService extends Service {
    // Binder given to clients
    private final IBinder mBinder = new LocalBinder();

     * 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;

    public IBinder onBind(Intent intent) {
        return mBinder;

Then in your activity bind to service in onStart callback, using ServiceConnection instance and unbind from it in onStop:

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

    protected void onCreate(Bundle savedInstanceState) {

    protected void onStart() {
        // Bind to LocalService
        Intent intent = new Intent(this, LocalService.class);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

    protected void onStop() {
        // Unbind from the service
        if (mBound) {
            mBound = false;

    /** Defines callbacks for service binding, passed to bindService() */
    private ServiceConnection mConnection = new ServiceConnection() {

        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;

        public void onServiceDisconnected(ComponentName arg0) {
            mBound = false;

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents