What are the services in Android systems and when are they used?
14 minute(s) read
Published on: Aug 02, 2021
Updated on: Dec 14, 2021
In applications intended for Android systems, the components of the applications are displayed to users when long and complex processes are performed. In this case, services are used. In other words, it can be said that when long-term processing needs to be done in the background and users can see them. It should be noted that services are one of the components that are most used in Android systems and are also used in more times when long and repetitive processing is done in the background of the Android system. What we mean by running in the background is that when the user even closes the application and opens another application, it runs again in the background. That is, when the application is closed, its activity is not interrupted, and it continues to operate behind the scenes or in the background. In short, we can say that services have no dependence on the life cycle of activities and can continue to operate without the need for them. Closing or opening the application and the desired program can not have any effect on the activity of services; This means that whether the program or application is open or closed, the service will continue to operate.
To better understand this issue, we will give you examples so that you can easily understand and understand them.
Consider a situation where, for example, a user has opened a song in a music player. In this case, when the user wants to go to other activities or open another activity, the music that was playing will stop. But the user wants the music to continue playing and the user can safely go to other activities and work with them. In this case, the services will help and continue their activities in the background.
In another example, consider the situation where the user wants to download a file, in which case the user must wait for the long download process to complete and then be able to go to other activities. This is tedious and tedious work, so we use the services so that we can continue long-term activities in the background and while continuing their activities in the background to other activities. When you use the Download Manager to download a file, you no longer must wait for the process to complete so that you can go to other activities, in which case you can activate other activities and use them at the same time as the Download Manager download process. By leaving this program, the download process will not stop, and users can easily continue their activities in other activities.
What are the different types of services in Android systems?
Services in Android systems are of two types:
1- Started Services
2- Bound Services
Started Services is related to the tasks that are defined for it, in that they only do the tasks that are intended for it and after that it does not do any other work. In other words, it is used to perform the intended activities and after completing that activity, it is no longer engaged in any other activity. It only does what it is supposed to do. It should be noted that this type of service is started by calling the startService and startForegroundService methods and its stopping is done by calling the stopService or stopSelf methods. In other words, we can say that in this type of service we can only use intent to start and stop services and we cannot have any other control and management on them. This service only allows us to start and stop, not to manage and control.
using this service, we can just launch or start an audio file and stop it, and we cannot control and manage it to see how much is left.
Unlike the service listed above, in this service, there is a possibility of interaction and communication between the service and the user, and users can communicate with the service and, if necessary, manage and control them. In this service, messages are exchanged between users and services, which is the connection and interaction between the user and the services. It should be noted that this service provides a client-server that can be used to establish communication and interaction between users and services. By using the client-server, it is possible for users to send their requests to it and receive the appropriate response in return. The connection between the service and the service component is established using the bindService method, and the connection between them is disconnected using the unbindService method. For example, using this service, we can check the status of the song that is being played, or what percentage of the file we download is finished and what percentage remains.
Therefore, unlike the previous service, this service can be managed and controlled.
Different types of Started Services
It should be noted that Started Services themselves are divided into two categories:
- Background Service:
This is a type of service that can perform processes in the background without the user's knowledge.
- Forground Service:
This is also a type of service that notifies the user when it is done and starts processing using Notification.
1- We create a new project in Android Studio and choose the desired name for it. The name chosen for this project in this part of the StartService tutorial.
2- The activity required for this project is Empty Activity. Select an activity of this type.
3- The language required for use in this project is Java. Select it to continue.
It should be noted that in this project that we are creating, we are going to play an audio file in the background, so that when the desired activity is closed or new activities are opened, the playback does not stop and continues.
4- We create three Buttons in the Active Layout section of the created project.
5- The codes that should be in the activity_main.xml section are as follows:
6- Then, we need to add a service class to the project. It should be noted that doing this is like adding a regular class to a project.
7- Right click on the project package folder.
8- Then go to New - Java Class. After going through this path, a class building window will be created.
9- Then we must consider the desired name for this created class. The name selected in this section for this class is MyService.
10- The class we have created must inherit from the Service class in the Android system.
11- To inherit from the Android Service class, enter the phrase Service in the Superclass field and then select the option related to android.app.
12- We do not change other options and build the class.
13- The class is added to the project next to MainActivity.
14- After successfully completing all the steps listed above, you will encounter an error.
15- It should be noted that the service class has many callback methods, but in this section, we must define the onBind method.
16- To do this, hold down the alt + insert key combination and select the Override Methods option to add the methods to the class automatically.
17- Add the onDestroy, onStartCommand, onCreate and onBind methods to the survey class.
18- The codes that should be in the MyService.java section are as follows:
19- First, I must add an audio file to the project so that I can play it and test the project.
20- To do this, right-click on the res folder.
21- Select the New option.
22- Then we must select Android Resource Directory or Directory.
23- Then select the raw option.
24- We will then see that the raw folder will be added to the res folder.
25- After creating that folder, we add an mp3 file to that folder.
26- Complete the Service class as follows.
27- The codes that should be in the MyService.java section are as follows:
In the code above, we first created an example of a MediaPlayer method with a custom name in this project, soundPlayer. This method is used to play audio files on Android systems. The onCreate method will be called when a service is first created using startService or bindService. That is why we include the code that needs to be executed once in this project.
In the code above, we specify the location of the audio file using MediaPlayer.create. In the next line of code above, I set the false value for setLooper so that the audio file is not played after it is finished.
The onStartCommand method returns the integer value. It should be noted that this value determines what state it will be in after the service is completed.
There are two values:
If this value is used and does not hold the service in the built-in state when the service is stopped. Holds the service in the build state after stopping when the startService is called. This option is used for services that have done a temporary job and do not need to repeat it.
Note that this value is kept in the built-in state after the service is stopped. This means that the onCreate and onStartCommand methods will be executed immediately. The value of intent is in this null.
In this type, like the second type, when it keeps the service system in a state of pause, it puts it in the build state and sets its intent equal to the last intent given to the method. This is used for cases where, for example, the service operation has stopped from somewhere, and for example, the music starts playing after it has stopped.
According to the explanations provided in the previous section, we choose the second type in this project.
28- Put the AndroidManifest.xml file inside the application tag.
Note that the service class name is considered as the value for the name.
29- The codes that should be in the AndroidManifest.xml section are as follows:
30- We complete the activity class as follows.
31- The code that should be in the MainActivity.java section is as follows:
In the code above, we have defined the start, stop and transfer buttons. We use intent to call Service using startService and stopService.
In the code above, we define an instance of Intent with the arbitrary name servIntent. The first input is context, the second parameter is service class.
Then we define a setOnClickListener for each of the buttons we define.
Inside onClick, we define the start button that we have defined, startService with servIntent input, and if we click on this button, first onCreate and then onStartCommand will be executed.
Inside the onClick button, we define stopService with the value of servIntent input, which if clicked on, the onDestroy method will be called and executed.
In the code above, we have defined another intent for the third button that can be moved from MainActivity to another activity.
We had to add another activity called ActivityTwo to the project.
32- We execute the project.
33- Click the Start button.
34- After clicking on it, first the message "Service created" and then "Service started" will be executed.
35- Click on the third button.
36- We will see that even if we exit the main activity, the audio file will be running and will not stop.
37- We leave the program.
38- After exiting the program, we will see that the audio file is running and has not stopped.
39- Then, if we click on the Stop button, the onDestroy method will be executed, which will stop the music playing.
40- To be able to see the list of running services, we must go to the Android settings section.
41- Go to Settings - Apps - RUNNING.
42- After following the path, we will see that we will have a list of running services.
It is worth noting that so far, we have been able to move forward successfully, but there is another problem. That is, if its resources are as scarce as the device memory, it may cause the service to stop without us pressing the button. That is, its scarcity of resources may cause it to stop before we can make changes to it manually. To solve this problem, we do the following.
43- We must take the service to Foreground mode. This is because the Android operating system gives more priority and importance to Foreground Services than Background Services, and this allows the services to be in Foreground Service mode and can be easily stopped by the system in case of lack of memory. , Continue their activities.
44- The startForeground method has two inputs, the first of which is an id of int and the second of which is a notification.
45- To do this, we need to design a notification.
46- The code that should be in the MyService.java section is as follows:
In the code above, we first define a Notification Channel.
47- We are implementing the project.
48- After we run the project and hit the start button, the related notification will be displayed in the status bar.
How to change services in Android?
For the Foreground Service to be compatible in Android 9, we must define the Permission in the project manifest section.
To give the Foreground Service permission to the program, we add the uses-permission tag with the value android.permission.FOREGROUND_SERVICE to the project manifest.
49- The codes that should be in the AndroidManifest.xml section are as follows:
50-Then we must run the project on Android operating system with version 9.
51- If we click on the Start button, a notification will appear, and music will be played. This means that Foreground Service is compatible with all versions of Android.DotNek Android development services