Codementor Events

Services in Android

Published Mar 29, 2018Last updated Apr 03, 2018
Services in Android

Android system has two types of services a started service and a bound service, both have a similar mechanism.
During the earlier days, I was so darn confused and got frightened that such complications do exist in the android community.Over the time, I conquered my fear and spent time on reading many blogs and slowly but surely I got hold of services in android.
Basically there are two types of services :

  1. Started Service
  2. Bound Services

Screen Shot 2018-03-29 at 10.47.49 PM.png

STARTED SERVICE

Started services are the most basic types of services. A service is called as a Started Service only when an activity calls the service using the function startService(). Once this service is called or opened it will run indefinitely in the background even if the component that started it is destroyed.
Basically there are different life cycle functions of an Android Service :
onStartCommand() - This method will be executed if the service is a started service.
onBind() - This method will be executed if the method is a bound service.
onCreate() - First method that is called whenever the service is called.
onDestroy() - This method will be called by the android system before destroying the service.
We override the onBind() method in all the services but in the case of the started services this method will return null.So developing a demo application to demonstrate the started services. Make an app that consists of two buttons labeled as start button and stop button.
An example of the started service is shown below :

public class StartedService extends Service {
   
   @Override
   public int onStartCommand(Intent intent, int flags, int startId) {

       Toast.makeText(this,"Service Started!!",Toast.LENGTH_LONG).show();
       return START_STICKY;
   }

   @Override
   public void onCreate() {
       super.onCreate();
   }

   @Override
   public void onDestroy() {
       Toast.makeText(this,"Service Stopped!!",Toast.LENGTH_LONG).show();
   }

   @Nullable
   @Override
   public IBinder onBind(Intent intent) {
       return null;
   }
}

How this is called from the Activity is shown below. Here the starty button calls the function startService() and the Stop Button calls the function stopService().

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    public void startService(View view) {
        Intent intent = new Intent(this,StartedService.class);
        startService(intent);
    }

    public void stopService(View view) {
        Intent intent = new Intent(this,StartedService.class);
        stopService(intent);
    }
}

It is clear from above that the service is called using the startService() therefore, this is a started service.

BOUND SERVICE

Bound services is the second classification of the services in Android System. This services imitates the Client-Server communication that takes place where the service acts as as a server and the activity or the android component that calls the service acts as a client.
We must create a user interface so that the service can interact with the activity or the android component. The interface is created in the service class which extends the Binder class since only the onBinder() method is being overridden in this case.
Here is how the Bound Service class looks like the interaction class is used as an interface so that the service can communicate with the activity and other components :

public class BoundService extends Service {

    private final IBinder binder = new InteractionService();

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    public class InteractionService extends Binder {

        BoundService getService() {
            return BoundService.this;
        }
    }

    public String getPrimaryMessage() {
        return "This is the primary message...!!";
    }

    public String getSecondaryMessage() {
        return "This is the secondary message...!!";
    }
}

Now seeing how the Activity or the components interact with this service.We need to create the service connection. An example of the activity is shown below :

public class MainActivity extends AppCompatActivity {


    BoundService boundService;
    boolean isBind = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent intent = new Intent(this,BoundService.class);
        bindService(intent,serviceConnection,BIND_AUTO_CREATE);

    }

    public void getFirstServiceMessage(View view) {
        String message = boundService.getPrimaryMessage();
    }

    public void getSecondServiceMessage(View view) {
        String message = boundService.getPrimaryMessage();
    }

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            BoundService.InteractionService interactionService = (BoundService.InteractionService) service;
            interactionService.getService();
            isBind = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            isBind = false;
        }
    };

    @Override
    protected void onStop() {
        super.onStop();
        if(isBind) {
            unbindService(serviceConnection);
            isBind = false;
        }
    }
}

Here is the difference between the Bound Service and Started Service.

Discover and read more posts from MOHIT KUMAR
get started
post comments2Replies
Jigyamarketing J
7 months ago

Technology Consulting Services in India | Jigya

Unlock your business potential with Jigya, a leading technology consulting firm in India. Our expert team offers comprehensive consulting services to drive innovation, streamline processes, and maximize efficiency for businesses of all sizes. Contact us to embark on your digital transformation journey today.

https://www.jigya.com/technology-consulting/

Versatile Mobitech
6 years ago

Great Share!

Versatile Mobitech is a Software Development Company based out of Hyderabad, We have pool of talented IT professionals who are technically sound in latest software development technologies like UX/UI Design, Website / Web Application Development, Mobile Applications Development, Digital Marketing and SEO, IT Consulting and Tech Support.

For more info visit: versatilemobitech.com