Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to bind a service with android components .

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 207
    Comment on it

    Sometimes when we are working with service then we want the service to communicate with android components like activity.We need to accomplish this task to bind service to an activity.This type of service called android bound service.Once service has bind to activity then it can return results back to activity from bind service.Here are some defined steps through which you will come to know how to bind a service to an activity and get results back to activity.

    Step-1 Create activity class that bind with service class by using of some override methods.

    import com.example.androidservicebindng.MyService.MyBinder;
    import android.app.Activity;
    import android.content.ComponentName;
    import android.content.Context;
    import android.content.Intent;
    import android.content.ServiceConnection;
    import android.os.Bundle;
    import android.os.IBinder;
    
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.TextView;
    
    
    
    public class MainActivity extends Activity {
        private MyService mBoundService;
        private boolean mServiceBound = false;
        private Button getDataFromServiceButton,stopServiceButton;
        private TextView messageTextView;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            messageTextView = (TextView) findViewById(R.id.messageTextView);
             getDataFromServiceButton = (Button) findViewById(R.id.startService);
             stopServiceButton = (Button) findViewById(R.id.stop_service);
    
    
    
             // when click this button then fetch data from MyService class 
             getDataFromServiceButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mServiceBound) {
                        messageTextView.setText(mBoundService.getData());
                    }
                }
            });
    
            stopServiceButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mServiceBound) {
                        unbindService(mServiceConnection);
                        mServiceBound = false;
                    }
                    Intent intent = new Intent(MainActivity.this,
                            MyService.class);
                    stopService(intent);
                }
            });
    
        }
    
        @Override
        protected void onStart() {
            super.onStart();
    
            // start service first then bind with current activity 
            Intent intent = new Intent(this, MyService.class);
            startService(intent);
            bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
        }
    
        @Override
        protected void onStop() {
            super.onStop();
            if (mServiceBound) {
                unbindService(mServiceConnection);
                mServiceBound = false;
            }
        }
    
    
    
        /* ServiceConnection class is used to establish or bind a connection to bind service through which return 
         * an object of MyService class hence we can operate a function of service class;
         */
    
        private ServiceConnection mServiceConnection = new ServiceConnection() {
    
            @Override
            public void onServiceDisconnected(ComponentName name) {
                mServiceBound = false;
            }
    
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                MyBinder myBinder = (MyBinder) service;
                mBoundService = myBinder.getService();
                mServiceBound = true;
            }
        };
    }
    

    Step-2 Create a layout to this class which have two buttons startService and stopService .

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#FFFFFF"
        android:orientation="vertical" >
    
        <Button
            android:id="@+id/startService"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:text="Start Service" />
    
        <Button
            android:id="@+id/stop_service"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Stop Service" />
    
        <TextView
            android:id="@+id/messageTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:textAppearance="?android:attr/textAppearanceLarge" />
    
    </LinearLayout>
    

    Step-3 Now defined a service class which will be bound to an activity.

     import android.app.Service;
    import android.content.Intent;
    import android.os.Binder;
    import android.os.IBinder;
    import android.util.Log;
    
    public class MyService extends Service {
        private static String LOG_TAG = "MyService";
        private IBinder mBinder = new MyBinder();
    
    
        @Override
        public void onCreate() {
            super.onCreate();
            Log.v(LOG_TAG, "in onCreate");
    
        }
    
        @Override
        public IBinder onBind(Intent intent) {
            Log.v(LOG_TAG, "in onBind");
            return mBinder;
        }
    
        @Override
        public void onRebind(Intent intent) {
            Log.v(LOG_TAG, "in onRebind");
            super.onRebind(intent);
        }
    
        @Override
        public boolean onUnbind(Intent intent) {
            Log.v(LOG_TAG, "in onUnbind");
            return true;
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
            Log.v(LOG_TAG, "in onDestroy");
    
        }
    
        public String getData() {
    
            return "Hi ,return from MyService ";
    
        }
    
        public class MyBinder extends Binder {
            MyService getService() {
                return MyService.this;
            }
        }
    }
    

    // In the above service class I have defined MyBinder class which inherit Binder class which in-turn implements IBinder interface.This class has a method which returns object of this MyService class. Any android components of application would be able to access public methods of this class.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: