Android bound service

  • bound service is started by calling bindService.
  • bound service doesn’t have an UI and it also running on the UI thread like a regular service.
  • bound service will stop when no components are binded to it anymore.
  • bound service can have multiple components bind to it.
  • bound service has components such as activity bind to it through a ServiceConnection, and use it to for communication.
  • bound service need an custom class which extends Binder.

Here is an example of bound service implementation in Android.

1. Create a class which extends from the Service,

public class BoundService extends Service {
    private static String LOG_TAG = "BoundService";
    private IBinder mBinder;
    private Random mGenerator;

    public void onCreate() {
        Log.v(LOG_TAG, "in onCreate");
        mBinder = new LocalBinder();
        mGenerator = new Random();

    public IBinder onBind(Intent intent) {
        Log.v(LOG_TAG, "in onBind");
        return mBinder;

    public void onRebind(Intent intent) {
        Log.v(LOG_TAG, "in onRebind");

    public boolean onUnbind(Intent intent) {
        Log.v(LOG_TAG, "in onUnbind");
        return true;

    public void onDestroy() {
        Log.v(LOG_TAG, "in onDestroy");
        mGenerator = null;

    public String getRandomNum() {
        return "Random Number: " + mGenerator.nextInt(10000);

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

2. Register it in the manifest.xml file in the application tag.

<service android:name=".BoundService"/>

3. Add the following in an Activity class. Assume the method boundService responds to a button click.

    BoundService mboundService;
    boolean mBound = false;
    public void boundService(View view) {
        String randomNum = mboundService.getRandomNum();
        Log.d("boundService", randomNum);
        Toast.makeText(this, randomNum, Toast.LENGTH_SHORT).show();

    protected void onStart() {
        // Bind to LocalService
        Intent intent = new Intent(this, BoundService.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) {
            BoundService.LocalBinder binder = (BoundService.LocalBinder) service;
            mboundService = binder.getService();
            mBound = true;

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

Search within Codexpedia

Custom Search

Search the entire web

Custom Search