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.

  • Exception when I run my application from Eclipse
  • ScrollingViewBehavior for ListView
  • Android: Click event for Status bar notification
  • Get active Application name in Android
  • Ionic get user's phone number
  • Layout width equal height
  • Related posts:

    Android Gradle DexException: Multiple dex files define Lorg/hamcrest/Description
    How to provide customized vibration on specific incoming calls
    Google Drive SDK for OCR
    Asynctask vs Thread in android
    I need an alternative option to HttpClient in Android to send data to PHP as it is no longer support...
    Get row position in onCreateContextMenu
  • Is it a bad idea to use printStackTrace() in Android Exceptions?
  • getLastKnownLocation returning NULL
  • Automatically accept all SDK licences
  • has text relocations. This is wasting memory and is a security risk. Please fix
  • Android Maps API v2 Change MyLocation Icon
  • Android Bluetooth Bluejacking Possible?
  • 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.