What is a service?
A service is an application component that can perform some lengthy operations in the background and does not provide a user interface. The service can be started by the components of other applications, even when the user switches to another application and keeps the background running. In addition, application components can be bound to services, interact with services, and even communicate interprocess (IPC). For example, services can handle network transmissions, music playback, perform file I/O, or interact with content provider, all in the background.
The difference between Service and Thread
A service is just a component that can still run in the background, even if the user no longer interacts with your application. Therefore, you should create a service only when you need it.
If you need to do some work outside the main thread, but only when the user interacts with your application, you should create a new thread instead of creating a service. For example, if you need to play some music, but only when your activity is running, you can create a thread in OnCreate (), start running in OnStart (), and then terminate the run in OnStop (). You might also consider using Asynctask or handlerthread to replace the traditional thread class.
since it is not possible to control the same Thread in different Activity , it is time to consider a service implementation. If you use a service, it runs in the main thread of the application by default. Therefore, if the service performs dense computations or blocking operations, you should still create a new thread in the service to complete (avoid ANR).
Classification of services by run
Front desk Service
Front-desk service refers to services that are often followed by the user, so when memory is low, it does not become the object to be killed. The front desk service must provide a status bar notification and will be placed under the "in Progress" ("ongoing") group. This means that the notification can be dismissed only after the service has been terminated or removed from the foreground.
For example, a player that plays music with a service should run in the foreground because the user is clearly aware of its operation. Status bar notifications may indicate which songs are currently playing and allow the user to initiate an activity to interact with the player.
To run your service request as a foreground, you can call the Startforeground () method. This method has two parameters: the integer value that uniquely identifies the notification, and the status bar notifies the notification object. For example:
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, NOTIFICATION);
To remove a service from the foreground, call the Stopforeground () method, which takes a Boolean parameter that indicates whether to remove the status bar notification at the same time. This method does not terminate the service. However, if you terminate the service while it is running in the foreground, the notification will be removed at the same time.
Classification by use
Local Service
Used within the application to implement some time-consuming tasks that do not occupy the application, such as the activity-owning thread, but rather a single-threaded daemon.
Call Context.startservice () to start, call Context.stopservice () to end. Internally you can call Service.stopself () or Service.stopselfresult () to stop yourself.
Remote Service
Applications that are used within the Android system can be reused by other applications, such as weather forecasting services, and other applications do not need to write such a service anymore. Interfaces can be defined and exposed for other applications to operate. The client establishes a connection to the service object and invokes the service through that connection. Call the Context.bindservice () method to establish a connection and start to call Context.unbindservice () to close the connection. Multiple clients can bind to the same service. If the service is not loaded at this time, bindservice () loads it first.
Service life cycle
Service life cycle methods:
Public class exampleservice extends Service { intMstartmode;//Identify the way the service was killed after deathIBinder Mbinder;//interface for client bindings BooleanMallowrebind;//Identify whether to use Onrebind @Override Public void onCreate() {//Service is being created}@Override Public int Onstartcommand(Intent Intent,intFlagsintStartid) {//Service is starting, raised by StartService () call returnMstartmode; }@Override PublicIBinderOnbind(Intent Intent) {//Client binding service with Bindservice () returnMbinder; }@Override Public Boolean Onunbind(Intent Intent) {//All clients are unbound with Unbindservice () returnMallowrebind; }@Override Public void Onrebind(Intent Intent) {//A client is using Bindservice () to bind to the service, //And Onunbind () has been called.}@Override Public void OnDestroy() {//service is not available, will be destroyed}}
Note that the Onstartcommand () method must return an integer. This integer is the description of how the system should continue to run after the service is killed. The return value of Onstartcommand () must be one of the following constants:
Start_not_sticky
If the system kills the service after Onstartcommand () is returned, the service will not be rebuilt unless there is an unsent intent. This is the safest option to avoid service runs when the service is no longer required and the application can simply restart those unfinished work.
Start_sticky
If the system kills the service after Onstartcommand () returns, it rebuilds the service and calls Onstartcommand (), but does not feed the previous intent again, but calls Onstartcommand () with a null intent. These remaining intent will continue to be sent, unless there are intent that have started the service. This applies to media players (or similar services), which do not execute commands, but need to be running and ready to stand by.
Start_redeliver_intent
If the system kills the service after Onstartcommand () returns, it rebuilds the service and calls Onstartcommand () with the last intent that was sent. Any intent that have not been sent will be fed in turn. This applies to active services that require immediate recovery, such as downloading files.
The life cycle of the service is very similar to the activity. However, it is more important that you pay close attention to the creation and destruction of services, because the services running in the background will not be noticed by the user.
The life cycle of a service-from creation to destruction-can have two paths:
A started service
This type of service is created by calling StartService () from other components. It is then kept running and must terminate itself by calling Stopself (). Other components can also terminate such services by calling StopService (). The system will destroy the service after it terminates.
If a service is started multiple times by the StartService method, the OnCreate method is only called once, OnStart will be called multiple times (corresponding to the number of calls StartService), And only one instance of the service is created (so you should know that only one stopservice call is needed). The service will always run in the background, regardless of whether the program's activity is running until it is called StopService, or its own Stopself method. Of course, if the system resources are insufficient, the Android system may end the service.
A bound service
The service is created by calling Bindservice () from other components (clients). The client then communicates with the service through a IBinder interface. The client can close the join by calling Unbindservice (). Multiple clients can bind to the same service, and when all the clients are unbound, the service is destroyed. (The service does not need to terminate itself.) )
If a service is started by an activity call Context.bindservice method binding, the OnCreate method is called only once, no matter how many calls Bindservice calls, and the OnStart method is never called. When the connection is established, the service will run until the call to Context.unbindservice disconnects or the Context of the previous call to Bindservice does not exist (for example, when activity is finished), The system will automatically stop the service and the corresponding OnDestroy will be called.
These two paths are not completely isolated. In other words, you can bind to a service that has been started with StartService (). For example, a background music service can be started by calling StartService () and passing in a Intent that indicates the music it needs to play. After that, the user may need to take some control with the player or need to view the current song's information, when an activity can bind to the service by calling Bindservice (). In such a case, StopService () or stopself () does not actually terminate the service unless all the clients are unbound.
When rotating the phone screen, when the phone screen in the "horizontal" "vertical" transformation, at this time if your activity will automatically rotate, the rotation is actually the activity of the re-creation, so the rotation before the use of Bindservice established connection will be broken (Context does not exist).
Declaring a service in manifest
No matter what type of service must be declared in manifest, the format is as follows:
... > ... ... > <service android:name=".ExampleService" /> ... </application></manifest>
The attributes of the Service element are:
Android:name ————-Service class name
Android:label ———— – The name of the service, if this is not set, the service name displayed by default is the class name
Android:icon ———— – Icon of the service
Android:permission ——-Affirm the permissions for this service, which means that only apps that have this permission available to control or connect to the service
Android:process ———-Indicates whether the service is running in another process, and if this is set, then the string will be appended to the package name to indicate the name of the other process.
Android:enabled ———-If this is set to true, then the Service will be booted by default, not set to False by default
Android:exported ——— Indicates whether the service can be controlled or connected by another application, and does not set the default to False
Android:name is the only required property-it defines the class name of the service. As with activity, a service can define a intent filter so that other components can invoke the service with implicit intent. If you want the service to be only used internally (other applications cannot call it), you do not have to (and should not) provide any intent filters.
In addition, if the Android:exported property is included and set to "false", you can ensure that the service is a private service for your application. This property remains in effect even if the service provides a intent filter.
StartService Start Service
You can start a service from activity or other application components, call StartService () and pass in a intent (specify the service you want to start).
new Intent(this, MyService.class); startService(intent);
Service class:
Public class myservice extends Service { /** * Onbind is a virtual method of Service, so we have to implement it. * Returns NULL, indicating that the client terminal cannot establish a connection to this service. */ @Override PublicIBinderOnbind(Intent Intent) {//TODO auto-generated method stub return NULL; }@Override Public void onCreate() {Super. OnCreate (); }@Override Public int Onstartcommand(Intent Intent,intFlagsintStartid) {//Accept the intent data passed over returnStart_sticky; };@Override Public void OnDestroy() {Super. OnDestroy (); }}
A started service must manage its life cycle on its own. That is, the system does not terminate or destroy such services unless the system memory must be restored and the service remains running after it returns. Therefore, the service must terminate itself by calling Stopself (), or another component can terminate it by calling StopService ().
Bindservice Start Service
When an activity or other component in an application needs to interact with the service, or if certain features of the application need to be exposed to other applications, you should create a bound service and complete it through interprocess communication (IPC).
Here's how:
Intent intent=new Intent(this,BindService.class); int flags)
Note that Bindservice is a method in the context and can be passed in when there is no context.
When a service binding is performed, its flags are:
Context.bind_auto_create
Indicates that when a binding request is received, if the service has not yet been created, it is created immediately, and the priority component is destroyed when the system is out of memory to free memory, and the service is destroyed only if the process hosting the service becomes a destroyed object.
Context.bind_debug_unbind
Typically used in debug scenarios to determine if the binding service is correct, but it is prone to memory leaks, so it is not recommended for debugging purposes
Context.bind_not_foreground
Indicates that the system will prevent the process hosting the service from having a foreground priority and running only in the background.
Service class:
Public class bindservice extends Service { //Instantiate Mybinder get Mybinder object; Private FinalMybinder Binder =NewMybinder ();/** * Returns binder object. */ @Override PublicIBinderOnbind(Intent Intent) {//TODO auto-generated method stub returnBinder }/** * New inner class Mybinder, inherited from binder (Binder Implementation IBinder interface), * Mybinder provides methods to return Bindservice instances. */ Public class mybinder extends Binder{ PublicBindserviceGetService(){returnBindservice. This; } }@Override Public Boolean Onunbind(Intent Intent) {//TODO auto-generated method stub return Super. Onunbind (Intent); }}
Activity code to start the service:
Public class mainactivity extends Activity { /** is bound * / BooleanMisbound =false; Bindservice Mboundservice;@Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main); Dobindservice (); }/** * Instantiate the implementation class of the Serviceconnection interface for monitoring the status of the service */ PrivateServiceconnection conn =NewServiceconnection () {@Override Public void onserviceconnected(componentname name, IBinder service) {Bindservice Mboundservice = ((bindservice.mybinder) service). GetService (); }@Override Public void onservicedisconnected(componentname name) {Mboundservice =NULL; } };/** Binding Service * / Public void Dobindservice() {Bindservice (NewIntent (mainactivity. This, Bindservice.class), conn,context.bind_auto_create); Misbound =true; }/** Unbind Service * / Public void Dounbindservice() {if(Misbound) {//Detach Our existing connection. Unbindservice (conn); Misbound =false; } }@Override protected void OnDestroy() {//TODO auto-generated method stub Super. OnDestroy (); Dounbindservice (); }}
Note that the service is explicitly declared in Androidmainfest.xml
To determine if the service is running:
privatebooleanisServiceRunning() { ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE); { if ("com.example.demo.BindService".equals(service.service.getClassName())) { returntrue; } } returnfalse;}
[Android] Full Service Summary