What is a service?
A service is an application component that runs in the background without a user interface to perform time-consuming operations. Other application components can start the service, and when the user switches to another scenario, the service will continue to run in the background. In addition, a component can bind to a service interaction with it (IPC mechanism), for example, a service may handle network operations, play music, manipulate file I/O, or with content providers
Provider) interaction, all of these activities are performed in the background.
Service has two states, "initiated" and "Bound"
The service runs in the main thread by default, so it is a child thread in the service instead of establishing a sub-thread to run the service.
Basic use of Service
Define a service: New class inherits service class
The Onbind method is required to be overwritten, while the other three are called at creation time, called when destroyed, called at startup
PublicClassMyServiceExtendsService {@OverridePublic IBinderonbind (Intent Intent) {return null ; } @Override public void oncreate () {super.oncreate ();} @Override public int onstartcommand (Intent Intent, int flags, int startid) {return super.onstartcommand (intent, flags, Startid); } @Override public void ondestroy () {super.ondestroy ();}}
Registering the service is also in the configuration file:
<service android:name=".MyService" />
Start the service and stop the service:
switch (v.getId()) { case R.id.button1: Intent startIntent =new Intent(this,MyService.class); startService(startIntent); break; case R.id.button2: Intent stopIntent =new Intent(this,MyService.class); stopService(stopIntent); break; }
Service itself to end itself:stopSelf();
If you want to service to complete what function, write in Onstartcommand method inside can.
Service communicates with activity:
You can use binder objects to communicate with each other by using the following method:
1. Create a new binder class in the service to inherit binder:
class MyBinder extends Binder{ public void MyStart(){ Log.d("Service", "MyStart: MyStart"); } }
- Returns an instance of this class in the Onbind method
private MyBinder mybinder; @Override public IBinder onBind(Intent intent) { return mybinder; }
- The next method of invoking the service in the activity is to bind the services first.
The parameters used for binding are connection;
private MyService.MyBinder myBinder; private ServiceConnection connection=new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) {//绑定调用 } @Override public void onServiceDisconnected(ComponentName name) {//j解绑调用 } };
Binding Service
case R.id.button3: Intent bindIntent=new Intent(this,MyService.class); bindService(bindIntent,connection,BIND_AUTO_CREATE); break; case R.id.button4: unbindService(connection); break;
Methods to invoke the service:
Written in onserviceconnected:
@Override public void onServiceConnected(ComponentName name, IBinder service) { myBinder=(MyService.MyBinder) service; myBinder.MyStart(); }
The life cycle of the service
As you can see from this diagram, the two ways to start the service and their life cycle, the bind service differs in that the corresponding service is killed when the bound component is destroyed. The service's declaration cycle is a lot simpler than the activity, as long as you understand the similarities and differences between the two startup service modes.
What is the basic understanding of 1.Service 1.1 service?
?? A service is a component that can perform long-running operations in the background without a user interface. It runs on the UI thread and therefore does not take time-consuming action.
1.2 The difference between service and thread
?? Service is run in the UI thread, is absolutely no time-consuming operation, and thread-enabled child threads can be time-consuming operation, but thread-enabled child threads are not directly to the UI to operate, or it is very likely to occur directly to the program to collapse, this is their difference.
2.2 ways to start Service 2.1 startservice () method to open service
?? Steps:
?? A. Define a class to inherit the service.
?? B. Configure the service in the Androidmanifest.xml file.
?? C. Use the StartService (Intent) method of the context to start the service.
?? D. When the service is no longer being used, call the StopService (Intent) method of the context to stop the service.
2.2 Bindservice method to open service (activity and service bindings)
?? Steps:
?? A. Create a binderservice server, inherit from the service and create an implementation instance object in the class that implements the IBinder interface and provide a public method to the client call.
?? B. Return this binder instance from the Onbind () callback method.
?? C. In the client, the binder is received from the onserviceconnected callback method and the binding service is invoked using the provided method.
Life cycle of 3.Service
?? There are two kinds of service life cycles, because services can be bound to activity or unbound, and activity and service can communicate, it is necessary to bind the service and activity. Therefore, the life cycle of the service is divided into unbound activity and bound activity.
Service life cycle diagram without binding activity:
Service life cycle diagram for binding activity:
1. Starting a service with the intent and StartService () method, the next execution of the OnCreate () method, when the service is first created, the system calls this method to execute a one-time Setup program (in Call Onstartcommand () or Onbind () Before). This method is not called if the service is already running.
2. This method is called when another component, such as Activity, initiates a service by calling the StartService () request. Once this method is executed, the service is started and can run indefinitely in the background. If you implement this method, you need to stop the service by calling Stopself () or StopService () after the service has finished working. (If you only want to provide bindings, you do not need to implement this method.) )
3. The service is in a running state.
4. An operation causes the service to stop, such as executing the Method StopService (), then the service performs ondestory () destruction. The service should implement this method to clean up all resources, such as threads, registered listeners, sinks, and so on. This is the last call received by the service.
5. The service is completely destroyed and the next step is to wait for it to be reclaimed by the garbage collector.
6. Starting a service through the intent and Bindservice () methods, the next execution of the OnCreate () method, when the service is first created, the system calls this method to execute a one-time Setup program (in Call Onstartcommand () or Onbind () Before). This method is not called if the service is already running.
7. This method is called when another component wants to bind to a service (for example, execute RPC) by calling Bindservice (). In the implementation of this method, you must provide an interface by returning IBinder for the client to use to communicate with the service. Be sure to implement this method, but if you do not want to allow binding, you should return NULL.
8. The service is in a running state. Successful binding with activity.
9. An operation causes the service to unbind, such as executing the Method Unbindservice (), then the service will then release the binding to the current activity. Next the service will face destruction.
10. The service Execution Ondestory () method is destroyed. The service should implement this method to clean up all resources, such as threads, registered listeners, sinks, and so on. This is the last call received by the service.
11. The service is completely destroyed and the next step is to wait for it to be reclaimed by the garbage collector.
For services, summarize:
A. The life cycle of the service being initiated: If a service is started by an activity call Context.startservice method, Then the service runs in the background regardless of whether or not activity is unbound to the service using Bindservice bindings or Unbindservice. 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.
B. The lifecycle of a service that is bound: if a service is started by an activity call Context.bindservice method binding, the OnCreate method is only called once, regardless of the number of calls Bindservice calls. The OnStart method is always not 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.
C. The life cycle of a service that is started and bound: If a service is also started and bound, it will continue to run in the background. And no matter how it is called, OnCreate is always called only once, how many times the service's onstart is called, and how many times the StartService is called. Calling Unbindservice will not stop the service, but must call StopService or the stopself of the services to stop it.
D. The purge service when a service is stopped: when one of the services is terminated (1, call stopservice;2, call stopself;3, no longer has a bound connection (not started)), the OnDestroy method will be called, where you should do some cleanup work, such as stopping a thread that is created and running in the service.
Special attention:
1, you should know that when the call Bindservice bound to the service, you should make sure to call Unbindservice in a certain place to unbind (although the Activity by the time the binding will be removed automatically, and the service will automatically stop);
2, you should pay attention to use StartService start the service, must use StopService stop service, regardless of whether you use Bindservice;
3, at the same time use StartService and bindservice to notice, service termination, need to unbindservice and stopservice simultaneously call, can terminate Service, regardless of StartService and The order in which Bindservice is called, if Unbindservice is called first, the service does not terminate automatically, then the service stops after calling StopService, and if StopService is called first, the service will not terminate, and then call Unbindservice or previously called Bindservice the Context does not exist (such as when the activity was finished) after the service will automatically stop;
4, when rotating mobile 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 re-creation, so the rotation before the use of Bindservice established connection will be disconnected (Context does not exist), the life cycle of the corresponding service is the same as above.
5, in the SDK 2.0 and later versions, the corresponding OnStart has been rejected into the Onstartcommand, but the previous OnStart still valid. This means that if you are developing an application with an SDK of 2.0 and later, you should use Onstartcommand instead of OnStart.
The difference between Service and thread
- Conclusion:
Service with Thread no relationship
- The reason why a lot of people will connect them, mainly because
Service of the background concept
Background: Background tasks run completely independent UI , even if the activity is destroyed/program is closed, as long as the process is still in, the background task can continue to run
- The similarities and differences between the two are as follows:
- Note: It is common
Service to Thread use and federate, that is, to Service create a sub-thread (worker thread) to handle the time-consuming operation logic, as in the following code:
@OverridePublicIntOnstartcommand(Intent Intent,int flags,int Startid) {New worker ThreadNew Thread (New Runnable () {@OverridePublicvoidRun() {Start the background Task}}). Start ();return Super.onstartcommand (intent, flags, Startid);} class Mybinder extends Binder { public void service_connect_activity() { // New worker thread new thread (newRunnable () { @Override public void Run() { //Perform specific download Task}}) . Start (); } }
Android Interview three service