A service is an application component that can be run in the background for a long time without interacting with the user. Other components can turn on the service, turn on the service to run on their own, and the user has switched to other applications. In addition, components can be bound to the service to interact. Timely is the cross-process interaction (Android's IPC mechanism). Network operations, playing music, running file IO operations, or interacting with content providers can be done through the service in the background.
Two types of service:
Started
by calling StartService (). You can start a service. Once started, the service can run independently in the background, even if the boot component is destroyed.
Typically, the service being started is used to run a single operation, and there is no return value. For example, download a file on the network.
When the operation has finished running. Service should end on its own.
Bound
by calling Bindservice (), you are able to bind a service. A bound service typically provides an interface for interacting with components, sending requests, getting results, and even interacting between processes (IPC).
The life cycle of the service being bound and its bound components are the same. Although multiple components can bind a service at the same time, but all of these components are unbound. Service will be destroyed.
Although the document typically describes two forms of service separately, you can open and bind the service at the same time.
Just need to overwrite two callbacks-onstartcommand and Onbind at the same time.
Regardless of the way you start the service (or both), you can use intent to operate the service, just like you do with activity.
However. Assuming you don't want other apps to use your service, you can declare the service as private in the manifest file, and see the service's statement in the manifest file for details.
Basic Introduction
To use a service, you need to inherit the service class or its subclasses.
You need to override some callback methods. At the same time, some key operations are performed in these methods. Here are some of the more important life cycle callback callbacks:
Onstartcommand ()
The system calls the function after you call the StartService. Once the method runs, the service is started and runs independently in the background. Assuming you implement this method, you must call Stopself () or StopService () at the appropriate time to stop the service. (Suppose you only provide a binding interface.) You can not implement this method)
Onbind ()
The system calls the Onbind () function when there are other components that bind the service through Bindservice ().
You need to provide a class that implements the IBinder interface to the client using this method. The method must be overwrite, assuming you do not want your service to provide binding functionality, you can return null directly.
The Android system forces the service to stop when memory is low, assuming that the service is bound to an activity that has focus. The risk of being killed is reduced, assuming that a service is declared as a front service. Then it would almost never be kill. No one. Assume that the service is open for a long time. As time goes by, the service will have a lower priority in the system. The higher the risk of being killed. Assuming your service is activated, you should consider the situation where it was killed by the system.
Suppose the system killed a service. So in the case of loose resources. The system restarts it (this is based on the policy you decide to restart on the return value of Onstartcommand ()).
Service's statement in the manifest file
As with activity, you need to declare the service in the manifest file.
... > ... ... > <service android:name=".ExampleService" /> ... </application></manifest>
Some other attributes can be declared in the service node. These properties are optional. It is only necessary to have android:name-this attribute is used to describe a unique service class name, and you should make sure that you do not change the class name.
To ensure the security of your app, you should use explicit intent to start or bind the service, and not declare intent-filters in the service.
In addition, you can ensure that your service is only available in your own app by setting the Android:exported property to False.
This can effectively prevent other applications from using your service, even through explicit intent.
to create a service as a starting mode
The service can be started by StartService (). You can hear the Onstartcommand () callback.
When a service is started, it will have a separate life cycle and run independently in the background. Even if the component that opened it was destroyed. In this case, you need to call Stopself () at the right time to end it or call Stopservie () to end it.
The intent that is passed when the call to StartService () is received at the Onstartcommand () callback.
Note: The service will run by default in the application process that declares the service. And will run in the main thread.
So assuming that your service is running some dense or clogged operations, it can cause the ANR phenomenon. In order to avoid such a situation. You need to open a new thread.
Generally speaking. You can accelerate your development by inheriting the Intentservice class.
inheriting the Intentservice class
Because most of the service does not need to handle concurrent requests. So you can accelerate your development by inheriting the Intentservice class.
Intentservice has the following characteristics:
1. A worker thread was created to run the intent passed by Onstartcommand (). The thread is detached from the main thread.
2. Create a task queue to run intent sequentially, so you don't need to consider multithreading.
3. When all tasks are completed, they will call Stopself () on their own initiative.
4. The default implementation of Onbind () is provided (return null)
5. The default implementation of Onstartcommand () is provided, sending tasks to the task queue and callback Onhandleintent ()
These features allow you to implement Onhandleintent () to complete the client task (you also need to provide a simple constructor)
Here is an implementation of Intentservice:
Public class hellointentservice extends intentservice { /** * A constructor is required, and must call the Super Intentservice (String) * constructor with A name for the W Orker thread. */ Public Hellointentservice() {Super("Hellointentservice"); }/** * The Intentservice calls this method from the default worker thread with a * the intent that started the Servic E. When this method returns, Intentservice * stops the service, as appropriate. */ @Override protected void onhandleintent(Intent Intent) {//Normally we would do some work here, like download a file. //For our sample, we just sleep for 5 seconds. Try{Thread.Sleep ( the); }Catch(Interruptedexception e) {//Restore interrupt status.Thread.CurrentThread (). interrupt (); } }}
Control. Suppose you inherit the code that you need to write from the service to implement the same functionality:
Public class helloservice extends Service { PrivateLooper Mservicelooper;PrivateServicehandler Mservicehandler;//Handler that receives messages from the thread Private Final class servicehandler extends Handler { Public Servicehandler(Looper Looper) {Super(Looper); }@Override Public void Handlemessage(Message msg) {//Normally we would do some work here, like download a file. //For our sample, we just sleep for 5 seconds. Try{Thread.Sleep ( the); }Catch(Interruptedexception e) {//Restore interrupt status.Thread.CurrentThread (). interrupt (); }//Stop the service using the Startid, so, we don ' t Stop //The service in the middle of handling another jobStopself (MSG.ARG1); } }@Override Public void onCreate() {//Start up the thread running the service. Note that we create a //separate thread because the service normally runs in the process ' s //main thread, which we don ' t want to block. We also make it //Background cpu-intensive work won't disrupt our UI.Handlerthread thread =NewHandlerthread ("Servicestartarguments", Process.thread_priority_background); Thread.Start ();//Get the Handlerthread ' s Looper and use it for our HandlerMservicelooper = Thread.getlooper (); Mservicehandler =NewServicehandler (Mservicelooper); }@Override Public int Onstartcommand(Intent Intent,intFlagsintStartid) {Toast.maketext ( This,"Service Starting", Toast.length_short). Show ();/For each start request, send a message to start a job and deliver the //Start ID so we know which request we ' re stopping when we finish the jobMessage msg = Mservicehandler.obtainmessage (); MSG.ARG1 = Startid; Mservicehandler.sendmessage (msg);//If We get killed, after returning from here, restart returnStart_sticky; }@Override PublicIBinderOnbind(Intent Intent) {//We don ' t provide binding, so return null return NULL; }@Override Public void OnDestroy() {Toast.maketext ( This,"Service Done", Toast.length_short). Show (); }}
Is not tired sleep does not love, decisive intentservice good ah.
However, suppose you want to implement concurrent operations that make the next request without waiting for the last request to run. It is necessary to inherit the service directly.
Note that the Onstartcommand () method must return an integer variable. This integer variable is used to specify how the system should return when it kills the service. The following are the individual return values:
Start_not_sticky
The service will not be created again after the system kills the service. Unless there is a need to pass pending intents. For service that can easily restart unfinished tasks when your program is ready.
Start_sticky
Assuming the system kills the service, then it restarts the service and calls Onstartcommand (), but does not send the previous intent again. Instead, it returns a null intent (unless it is a pending intents. This mode is ideal for music players such that no need to run commands. But the service needs to run independently and wait for the task.
Start_redeliver_intent
Assuming the system kills the service, it then restarts the service and then the Onstartcommand (), and passes the previous intent. This model is suitable for those service that need to be returned immediately, than for example to download the file.
to start the service in a binding manner
See the-bound Services for Android development document translation
send notifications to users
Once the service runs, you can tell the user about certain events through toast notifications or status Bar notifications.
Toast Notifications is a message that appears on the surface of the current form in a short time. Status bar Notifications is a notification bar that provides icons and messages that users can click to run an action (such as opening an activity)
Front desk Service
The front service pass is often used to run some operations that require the user to be aware of the operation, so the system does not kill the service in low memory state.
The front service needs to provide a notification on the status bar that will not disappear until the service is stopped or removed from the foreground.
For example, the music player service should be set to run in front of the service, because the user should always be aware of this operation. The status bar should show the currently playing song, and you should jump to the activity that interacts with the user after the current click.
You can have your service run in the foreground by calling the Startforeground () function. Use the scale as follows:
Notification Notification = new Notification (R. drawable. Icon, GetText (R. String. Ticker_text), System. Currenttimemillis());Intent notificationintent = new Intent (This, exampleactivity. Class);Pendingintent pendingintent = pendingintent. Getactivity(This,0, Notificationintent,0);Notification. Setlatesteventinfo(This, GetText (R. String. Notification_title), GetText (R. String. Notification_message), pendingintent);Startforeground (ongoing_notification_id, NOTIFICATION);
Manage the service life cycle
The service life cycle is much simpler than activity. But you need to pay more attention to it. Because the service is usually running in the background.
The service life cycle is generally divided into the following two types:
The life cycle of the service is as seen.
SOURCE Link: Android API documentation Services
-services of Android Development document translation