Service in Android – Basics – Part 1

Tram Ho

Have you ever wondered why the Android application has been exited, turned off, and the music is still running, is the download still executed? That’s strange isn’t it because we no longer see that app. So why is that possible? The answer is very simple. Android has provided us with a component that is Service – service. The article will go into understanding the concept, classification and implementation of the Service. The following is part one.

The article is also posted at his blog: https://codecungtrung.com

I. Concept

1. What is Service?

Service is a component of Android, created by the system, can perform operations … long in the background and does not provide a user interface, can operate even when the application is canceled.

Another application component can launch a service, and it will continue to run in the background even if the user moves to … other applications.

2. Why use?

In the definition provided for us the reason for using the service. Such as network processing, playing music, inputting files, etc. are all in the background

* Tips * There is a small for this section is:

The service runs in … the main thread of the process contains it (the process can contain multiple threads). The service does not create its own thread, nor does it run in a separate process unless you create it. So normally it will run in … Main UI Thread .

So if you want to perform a heavy task, consume CPU, wait for results, … should create a new thread in the service to do that, avoid ANR (Application Not Responding) error.

 

II. Service classification

In the past, people used to divide into Unbound Service and Bound Service. But now there is a new classification as follows:

  • Foreground service : performs tasks that the user may notice, recognize and must display a Notification. For example, an application that plays music, the part the user knows is the music emitted. The Notification section will display the current song name, allowing users to skip tracks, stop music, …
  • Background service : perform user actions … without direct attention. Since Android 8.0, services running in the background are limited
  • Bound service : provides a Client – Server interface that allows components to interact with it: send requests, receive results and even IPC (inter-process communication) – communicate through many processes.

Here I will go into details of each type

1. Unbound Service (foreground + background service)

a. Use

I included two types of foreground and background service into this section – unbound service because these two types … are basically the same. If you have any comments, feel free to comment below, very welcome!

Unbound means … no strings attached. Unbound service is a service that will run long, not tied to the interface component start it and … still run even if that component is destroyed. That’s when you completely delete the app from recent applications – canceled, but the music is still running, the file is still downloading.

Starting with Android 8.0, unbound services without an accompanying notification will not be allowed to function when the activity is lost. At that time you will have to create a foreground service as referred to above and startForegroundService () and startForeground ().

b. Life cycle

Unbound service life cycle

onCreate ()Called by the system when the service is started for the first time. You can initialize the objects needed for your service here
onStartCommand ()The system calls this method when another component, such as an Activity, requests the start service. The jobs you want the service to do will be implemented here.
onDestroy ()The system calls this method when the service is no longer in use and is being destroyed. You should remove unnecessary objects, clean up memory here.

Tips

  • Start service with startService () or startForeGroundService () – use it starting in Android 8.0
  • A context called startService ():

If the service has not been created, it will call onCreate () -> onStartCommand ()

If that service was created -> don’t call onCreate () but call onStartCommand () always

=> Start how many times … only one instance of the service is created

There are frequently used flags for the return of the onStartCommand function, which will help the operating system decide when the phone is out of memory and other tasks are needed:

  • START_STICKY : Tell the operating system that you need to recreate the service when you have enough memory and call onStartCommand () again with … the intent is null.
  • START_NOT_STICKY : Tell the operating system that … there is no need to recreate the service
  • START_REDELEVER_INTENT : If the Service is killed, it will be restarted with an Intent that is the last Intent that the Service was received. This is suitable for services that are performing tasks that want to continue immediately such as downloading fie
  • START_STICKY_COMPATIBILITY : same as START_STICKY but it is not sure, restart the service.

c. Code

The code for this section is quite simple, will include the following steps:

  • Declaring service in AndroidManifest
  • Extend the Service class, rewrite the functions onCreate (), onStartCommand () and onDestroy () as described in the life cycle section.
  • Then on the Client side just call startService (intent) to start the service or stopService (intent) to stop the service.

For more details, please refer to the end of the post offline ?

d. stopService (intent) vs stopSelf () vs stopSeft (startId)

  • stopService (intent): helps you stop the service, but calls outside the service you want to stop
  • stopSeft (): helps you stop the service, but call inside the service Every time you call startService (), in onStartCommand () has startemd paremater, it will be increased by 1 unit. Or not yet ?
  • stopSeft (startId): helps you stop the current service, but only if the service startId id coincides with be … last start. This means that you start a request to the service and when finished processing you for example stopSelf (). But between that time you start another request and when it has not yet finished processing, you have stoppedSelf () above so of course it … will go away. => If stopSeft (startId) is used, then the time when the stop is stopped will be the middle alternating request

=> Everything will work ok !!!

This is all about unbound service. If you have any comments on what you write, leave a comment below. Now, let’s continue to learn Bound service! Let’s go !!!

2. Bound service

a. Use

Interpretation of bound service : bound means binding. Unlike the unbound service above, when all clients call unbind to the service – to disconnect from it or those clients are destroyed then … the service is also canceled.

=> The service life cycle depends, bound (bound) to the life cycle of the Client. This is the meaning of that bound service name.

Bound service is deployed as a Client – Server model (you’ve probably heard of it, haven’t you ?). The figure below illustrates how this works

  • Clients will be bind objects that bind to services. In the figure that is Activity, it requires Service to get GPS coordinates
  • The server is the service , which will perform the task, then return the results to the client . In the figure, the Service will make a call to the GPS Module, receive the results and then send it back to Activity (Client).

In this part, I have used 2 words unbind and bind (which will correspond to 2 methods, unbindService () and bindService ()). Many of you will probably wonder what it is for. (although I have explained it shortly after). So in the next section, I will explain more clearly ?

b. Life cycle

Bound service life cycle

onCreate ()Similar to Unbound service above
onBind ()The service calls this method when … another component wants to bind to it by calling bindService (). The function will return an IBinder object. With unbound service, you will return null.
onUnbind ()The system calls this method when all clients are disconnected from the service. Want to disconnect from the service you will call unbindService (), or just you … destroy the client – do not call unbindService (). However, this is not advisable: 3
onRebind ()The system calls this method when the new Client has connected to the service, after having previously been notified that all were disconnected in onUnbind (Intent). Note that when onUnbind () returns true, this method will be called
onDestroy ()Call this method when all clients call unbind to the service or they have been canceled. You should remove unnecessary objects, clean up memory here.

Some tips in this section are:

  • You can connect multiple clients to the service simultaneously. But … the onBind () function will only be called to create an IBinder object when the first client binds (wow). The reason is that the system has … cached the IBinder object for the first time. So when the other clients link to just take it out and send it, save the effort to call back ?

Conclusion

Service is a component of Android, created by the system, can perform operations … long in the background and does not provide a user interface, can operate even when the application is canceled.

In the past, people used to divide into Unbound Service and Bound Service . But now there are 3 new categories: Foreground service, Background service and Bound service. But basically still the 2 types above.

Unbound service and bound service have their own usage and life cycle. Need to understand each type to apply properly.


The article is quite long, thank you for reading here ?

If you have any comments on the content of the article, please leave it at the bottom. Hope to receive your contribution can be more perfect. Thank you ?

In Part 2, we will continue to learn about Bound Service, how to initialize it, some notes and some other useful information.

Refer

Code for bound service: https://developer.android.com/guide/components/services#Declaring

Changes in Android 8.0 https://developer.android.com/about/versions/oreo/background

Service Overview https://developer.android.com/reference/android/app/Service.html


See more of his other posts at

On personal blog: Code with Trung

Share the news now

Source : Viblo