Android “Services” Frequently Asked Interview Questions Part 2 of. N
I Have taken most of the questions from people’s interview reviews from glassdoor and combining them in one place.
1.What is the service in android? and use of service?
Ans: A service is an application component that can perform long-running operations in the background. It does not provide a user interface. Once started, a service might continue running for some time, even after the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC). For example, a service can handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.
2.What are the types of services?
Ans: There are 3 types of services
- ForgroundService: A foreground service performs some operation that is noticeable to the user. For example, an audio app would use a foreground service to play an audio track. Foreground services must display a Notification. Foreground services continue running even when the user isn’t interacting with the app. When you use a foreground service, you must display a notification so that users are actively aware that the service is running. This notification cannot be dismissed unless the service is either stopped or removed from the foreground.
- BackgroundService: A background service performs an operation that isn’t directly noticed by the user. (Started and Intent Service)
- BoundService: A service is bound when an application component binds to it by calling bindService(). A bound service offers a client-server interface that allows components to interact with the service, send requests, receive results, and even do so across processes with interprocess communication (IPC). A bound service runs only as long as another application component is bound to it. Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed.
3.What is started service?
Ans: A service is started when an application component, such as an activity, starts it by calling startService(). Once started, a service can run in the background indefinitely, even if the component that started it is destroyed.
4.What is the intent service?
Ans: A Intent service is a special type of service, It creates its own thread and executes work in a separate thread, So in this, you explicitly don't create the thread. It has on handle intent() method which gets a callback once you start a service, Does the same work as started service but get destroy once work has been finished.
5.In which thread services run?
Ans: By default Started and Bind services run in the main thread, Only the intent service creates a different thread.
6.Difference between Service, Thread, and AsyncTask?
Service: A service is simply a component that can run in the background, even when the user is not interacting with your application, so you should create a service only if that is what you need.
Android system maintains the service so if any resource crunch situation occurs so System will re-start your service.
Service is a component of android, so it has priority levels to be considered while destroying an application due to low memory.
We have the Context available in service.
By default runs on the main thread.
Can have common code for multiple modules.
Have the APIs to communicate to service and other components.
Thread: A Thread can be used to perform any task which may need to perform in another thread other than the main.
Tread has no default mechanism to get the data back from it(Need to use Handler).
If the thread destroys by the system then it will not restart again.
AsyncTask: It is an API provided by the android which smart uses a thread inside it and combines both main and background thread into one and allows us to use the communication with minimal effort.
AsycTask will be associated with the activity itself, with No reusable code.
7.Explain the service lifecycle?
To create a service you need to create a class that will be extending service class and needs to override some method to achieve your work done by service.
- onCreate(): The system invokes this method to perform one-time setup procedures when the service is initially created. If the service is already running, this method is not called.
- onStartCommand(): The system invokes this method by calling
startService()when another component (such as an activity) requests that the service be started. When this method executes, the service is started and can run in the background indefinitely. If you implement this, it is your responsibility to stop the service when its work is complete by calling
stopService(). If you only want to provide binding, you don't need to implement this method.
- onBind(): The system invokes this method by calling
bindService()when another component wants to bind with the service (such as to perform RPC). In your implementation of this method, you must provide an interface that clients use to communicate with the service by returning an
IBinder. You must always implement this method; however, if you don't want to allow binding, you should return null.
- onDestroy(): The system invokes this method when the service is no longer used and is being destroyed. Your service should implement this to clean up any resources such as threads, registered listeners, or receivers. This is the last call that the service receives.
- onUnbind(): The system calls this method when all clients have disconnected from a particular interface published by the service.
- onRebind(): The system calls this method when new clients have connected to the service after it had previously been notified that all had disconnected in its onUnbind(Intent).
8.What is IBinder Interface and its uses?
Ans: Base interface for a remote object, the core part of a lightweight remote procedure call mechanism designed for high performance when performing in-process and cross-process calls. This interface describes the abstract protocol for interacting with a remote object. Do not implement this interface directly, instead extend from
The main use is to enable communication from service to other components.
9.What is the use of a service connection?
Ans: ServiceConnection is an interface which is having some utility method to enable communication from service and other components
It has 2 main methods to enable communication, You have to implement this method and provide the implementation.
- onServiceConnected(ComponentName name, IBinder service): Called when a connection to the Service has been established, with the
IBinderof the communication channel to the Service.
2. onServiceDisconnected(ComponentName name): Called when a connection to the Service has been lost.
10.Different intent flags while starting a service(Sticky, NotSticky, Re-deliver)?
- START_NOT_STICKY: If the system kills the service after
onStartCommand()returns, do not recreate the service unless there are pending intents to deliver. This is the safest option to avoid running your service when not necessary and when your application can simply restart any unfinished jobs.
- START_STICKY: If the system kills the service after
onStartCommand()returns, recreate the service and call, but do not redeliver the last intent. Instead, the system calls
onStartCommand()with a null intent unless there are pending intents to start the service. In that case, those intents are delivered. This is suitable for media players (or similar services) that are not executing commands but are running indefinitely and waiting for a job.
- START_REDELEVER_INTENT: If the system kills the service after
onStartCommand()returns, recreate the service and call
onStartCommand()with the last intent that was delivered to the service. Any pending intents are delivered in turn. This is suitable for services that are actively performing a job that should be immediately resumed, such as downloading a file.
11.Service inheritance hierarchy?
12.How to access the service from outside the app?
Ans: You have to create a fully qualified component name and can trigger service and service should be exported true in manifest.
13.Can we start a service from the broadcast Receiver class?
Ans: Yes you can start a service from a broadcast Receiver but binding is not preferred.
14.What is the result receiver?
Ans: Android ResultReceiver is used to receive callback results from services. It’s mainly used in intent service.
You have to override onReceiveResult(int resultCode, Bundle resultData) method and make the use of receiver.send(DOWNLOAD_SUCCESS, bundle) method in service, Implement this interface in your activity to get the data.
15.Can we start the service again?
Ans: Service will have only one instance throughout the app lifecycle.
Here are some key notes:
- In many cases, using WorkManager is preferable to using foreground services directly.
- If your app targets API level 26 or higher, the system imposes restrictions on running background services when the app itself isn’t in the foreground. In most situations, for example, you shouldn’t access location information from the background. Instead, schedule tasks using WorkManager.
- Remember that if you do use a service, it still runs in your application’s main thread by default, so you should still create a new thread within the service if it performs intensive or blocking operations.
- To ensure that your app is secure, always use an explicit intent when starting a
Serviceand don't declare intent filters for your services. Using an implicit intent to start a service is a security hazard because you cannot be certain of the service that responds to the intent, and the user cannot see which service starts. Beginning with Android 5.0 (API level 21), the system throws an exception if you call
bindService()with an implicit intent.
- You can ensure that your service is available to only your app by including the
android:exportedattribute and setting it to
false. This effectively stops other apps from starting your service, even when using an explicit intent.
- A started service is one that another component starts by calling, which results in a call to the service's
- If your app targets API level 26 or higher, the system imposes restrictions on using or creating background services unless the app itself is in the foreground. If an app needs to create a foreground service, the app should call
startForegroundService(). That method creates a background service, but the method signals to the system that the service will promote itself to the foreground. Once the service has been created, the service must call its
startForeground()method within five seconds.
- Once requested to stop with
stopService(), the system destroys the service as soon as possible.
onDestroy()methods are called for all services, whether they're created by