bind/unbind service example (android)

can you give me a simple example of application with background service which uses bind/unbind methods to start and stop it? i was googling for it for an halfhour, but those examples uses startService/stopService methods or are very difficult for me. thank you.

  • Android long key press
  • Local image caching solution for Android: Square Picasso vs Universal Image Loader
  • ASP.NET Web API Authentication
  • Sliding menu locks touch event on upper view
  • Try to Understand the behavior of BottomSheet in android support library 23.2.1
  • Encrypting files with AES on Android
  • Related posts:

    Varying windowSoftInputMode for fragments inside the viewpager
    no resource found that matches the given name
    Android C++ NDK
    Android - How to stop animation between activity changes
    import cannot be resolved
    Debug android device via Bluetooth
  • unable to make connection between 2 device bluetooth android
  • How do I write outputs to the Log in Android?
  • OnLocationChanged callback is never called
  • Android Studio shows red exclamation at drawable attribute
  • Abrupt scrolling with NestedScrollView in ViewPager Fragment inside a CoordinatorLayout Android
  • AppCompatEditText.getpParent() inside TextInputLayout returns FrameLayout
  • 3 Solutions collect form web for “bind/unbind service example (android)”

    You can try using this code:

    protected ServiceConnection mServerConn = new ServiceConnection() {
        public void onServiceConnected(ComponentName name, IBinder binder) {
            Log.d(LOG_TAG, "onServiceConnected");
        public void onServiceDisconnected(ComponentName name) {
            Log.d(LOG_TAG, "onServiceDisconnected");
    public void start() {
        // mContext is defined upper in code, I think it is not necessary to explain what is it 
        mContext.bindService(intent, mServerConn, Context.BIND_AUTO_CREATE);
    public void stop() {
        mContext.stopService(new Intent(mContext, ServiceRemote.class));

    Add these methods to your Activity:

    private MyService myServiceBinder;
    public ServiceConnection myConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder binder) {
            myServiceBinder = ((MyService.MyBinder) binder).getService();
        public void onServiceDisconnected(ComponentName className) {
            myService = null;
    public Handler myHandler = new Handler() {
        public void handleMessage(Message message) {
            Bundle data = message.getData();
    public void doBindService() {
        Intent intent = null;
        intent = new Intent(this, BTService.class);
        // Create a new Messenger for the communication back
        // From the Service to the Activity
        Messenger messenger = new Messenger(myHandler);
        intent.putExtra("MESSENGER", messenger);
        bindService(intent, myConnection, Context.BIND_AUTO_CREATE);

    And you can bind to service by ovverriding onResume(), and onPause() at your Activity class.

    protected void onResume() {
        Log.d("activity", "onResume");
        if (myService == null) {
    protected void onPause() {
        //FIXME put back
        Log.d("activity", "onPause");
        if (myService != null) {
            myService = null;

    Note, that when binding to a service only the onCreate() method is called in the service class.
    In your Service class you need to define the myBinder method:

    private final IBinder mBinder = new MyBinder();
    private Messenger outMessenger;
    public IBinder onBind(Intent arg0) {
        Bundle extras = arg0.getExtras();
        // Get messager from the Activity
        if (extras != null) {
            Log.d("service","onBind with extra");
            outMessenger = (Messenger) extras.get("MESSENGER");
        return mBinder;
    public class MyBinder extends Binder {
        MyService getService() {
            return MyService.this;

    After you defined these methods you can reach the methods of your service at your Activity:

    private void showServiceData() {  

    and finally you can start your service when some event occurs like _BOOT_COMPLETED_

    public class MyReciever  extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals("android.intent.action.BOOT_COMPLETED")) {
                Intent service = new Intent(context, myService.class);

    note that when starting a service the onCreate() and onStartCommand() is called in service class
    and you can stop your service when another event occurs by stopService()
    note that your event listener should be registerd in your Android manifest file:

    <receiver android:name="MyReciever" android:enabled="true" android:exported="true">
                <action android:name="android.intent.action.BOOT_COMPLETED" />

    First of all, two things that we need to understand,


    • It makes request to a specific server

    bindService(new Intent(""),
    mServiceConn, Context.BIND_AUTO_CREATE);

    here mServiceConn is instance of ServiceConnection class(inbuilt) it is actually interface
    that we need to implement with two (1st for network connected and 2nd network not connected) method to monitor network connection state.


    • It handles the request of the client and makes replica of its own which is private to client only who send request and this raplica of server runs on different thread.

    Now at client side, how to access all the methods of server?

    • Server sends response with IBinder Object. So, IBinder object is our handler which accesses all the methods of Service by using (.) operator.


    MyService myService;
    public ServiceConnection myConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder binder) {
            myService = binder;
        //binder comes from server to communicate with method's of 
        public void onServiceDisconnected(ComponentName className) {
            myService = null;

    Now how to call method which lies in service


    Here myService is object and serviceMethod is method in service.
    and by this way communication is established between client and server.

    Android Babe is a Google Android Fan, All about Android Phones, Android Wear, Android Dev and Android Games Apps and so on.