What do you need to know about parsing services?

Source: Internet
Author: User

What do you need to know about parsing services?

What is Service?

Service. In the Android system, the Service and Activity are similar to each other. For the Activity, you will certainly be familiar with it. The most involved in Android Application Development is Activity. So today we use Activity to introduce the Service. Like Activity, Service is one of the four major components of Android and must be registered in the AndroidManifest configuration file. The Service is not a Service that runs in the background like the Activity at the front end. If the Activity is used as the user interaction interface for downloading the software, the Service is the download thread that runs silently in the background, so the application scenario of the Service is when we don't need it to stay at the frontend but need it to work in the background all the time, such as downloading and playing music, listening to client messages by IM software, etc.

Service Startup

There are two ways to start the Service, not monotonous and luxurious. In components, we can start the Service using startService (), which is similar to the Activity startup method, and use stopService () to close the started Service; of course, you can also use bindService (), a unique binding and starting method, to start the Service. The corresponding unbinding method is naturally unbindService (). Of course, the difference between the two startup methods also means that the Service has different life cycle calling methods. Let's take a look at the Service Startup code, as shown below:

Define a Service class:

1 public class MyService extends Service {2 // onBind is the required abstract method 3 @ Override 4 public IBinder onBind (Intent arg0) {5 return new MyBinder (); 6} 7 @ Override 8 public void onCreate () {9 super. onCreate (); 10} 11 @ Override12 public void onDestroy () {13 super. onDestroy (); 14} 15 @ Override16 public void onRebind (Intent intent) {17 super. onRebind (intent); 18} 19 @ Override20 public void onStart (Intent intent, int startId) {21 super. onStart (intent, startId); 22} 23 @ Override24 public boolean onUnbind (Intent intent) {25 return super. onUnbind (intent); 26} 27/** 28 * construct a MyBinder class, which inherits from the Binder, the Binder implements the IBinder interface 29 */30 public class MyBinder extends Binder {31 // returns the reference of the Service instance 32 public MyService getId () {33 return MyService. this; 34} 35} 36}

StartService:

// Start a ServiceIntent intent = new Intent (this, MyService. class); startService (intent); // stop ServicestopService (intent );

The lifecycle of startService () is as follows:

Context. startService ()-> onCreate ()-> onStart ()-> Service Running-> context. stop ()-> onDestroy ()-> Service Disabled

The start method is bindService:

You must first construct a connection class that implements the ServiceConnection interface.

1 private class MyServiceConnection implements ServiceConnection {2 public MyServiceConnection () {}3 @ Override 4 public void onServiceConnected (ComponentName arg0, IBinder binder) {5 MyService Myservice = (MyService. myBinder) binder ). getService (); 6 // call 7} 8 @ Override 9 public void onServiceDisconnected (ComponentName arg0) {10 // call 11} 12 when the service crashes}

Then bind and start the Service.

// Bind a ServiceIntent intent = new Intent (this, MyService. class); MyServiceConnection conn = new MyServiceConnection (); bindService (intent, conn, Context. BIND_AUTO_CREATE); // unbind ServiceunbindService (conn );

After bindService () is executed, the system will call onCreate () and onBinde (). After onBind () is executed, the onServiceConnected () method in ServiceConnection will be called back, at the same time, return a class that implements the IBinder interface (generally, it will return the subclass inherited to the Binder, because the Binder implements the IBinder Interface), and then we can use some means (refer to the above Code) getting the Service instance from IBinder is equivalent to obtaining control once the reference is obtained. Then, it is not your own business to play with the Service...

BindService () Startup Mode lifecycle:

Context. bindService ()-> onCreate ()-> onBind ()-> Service Running-> context. unBindService ()-> onUnbind ()-> onDestroy ()-> Service is Disabled

The above two life cycles are very formal execution procedures, but the philosophy tells us that there are common exceptions, so there are some wonderful life flows.

Scenario 1:When we call startService () in the component to start the Service, but we didn't call stopService () to destroy the Service, we are again startService () when you start the service, the onCreate () callback method is not called, but the onStart () method is only executed (). Why? In the Android system, each Service is set to the singleton mode. No matter how many times startService () is called to start the Service, only one Service will be run in the system. OnCreate () is called when the Service is created. Therefore, the onCreate () Service is not called when the Service is started multiple times because the Service already exists in the system, therefore, only onStart () is called (). That is to say, when the service is started multiple times, onCreate () is called only once, while onStart () can be called multiple times.

Scenario 2:When we need to sweep out the Service started through startService (), the call of stopService () can meet our small requirements. At this time, the program is generally as expected to execute onDestroy (). But if we didn't sacrifice the sword stopService (), but killed the caller (such as Activity) directly, will the onDestroy () method be executed? The answer is no, because since the Service is started, the Service has a clear relationship with the caller. no matter whether the caller is physically ill or physically ill, it has nothing to do with him unless the stopService () is played () the intent (intent) is used to reclaim the Service. Of course, this is based on the premise that the Service is started through startService.

Case 3:Now let's talk about bindService, which is the same as startService. if the Service is repeatedly started multiple times, onCreate () will only call the first time that the Service is created. OnBind () is called every time the service is bound repeatedly. Here, onBind () is primarily used to transmit Ibinder back to the biner, use it to establish a contact between the binding person and the Service. If multiple bindings exist, executing unbindService () will only trigger onUnbind (), but will not trigger onDestroy (). Only the last bind will call unbindService () this will trigger the onDestroy () call of the service. Another special feature is that, if you destroy a binding person (such as Activity), the bound Service will follow him (onUnbid-> onDestroy ).

Tips on Service

1. If you need a method that will not be destroyed after the caller exits, but you need to obtain its reference at the same time, there is such a small method. StartService () starts the Service, bindService binds the Service, you can get the reference of the Service, and then unbindService is unbound. Because startService is used, only onUnbind () is executed (), in this case, because there is no binding relationship, even if the caller fails, the Service is still running as old.

2. Although the Service is running in the background, it is still running in the main thread, the main thread is running its onCreate, onStart, onBind and other life cycle methods in the main thread. If these methods perform time-consuming work such as downloading and reading large files, this will cause the main thread to be blocked. Therefore, we generally run the services we need in another sub-thread in the Service.

3. Start, bind, stop, and unbind a Service must be in the corresponding life cycle of the caller. For example, a Service needs to run through the entire Activity, we can start or bind a Service in onCreate, stop or unbind the Service in onDestroy. If you only need to run the service at the user's front-end, you should perform corresponding processing in onStart and onStop. We do not recommend that you start or stop the service in onPause and onResume, because this may cause unnecessary performance consumption. For example, when two activities need this service at the same time, when onPause of the previous activity just ends the service, the next activity immediately starts the service in onResume, causing some nausea.

4. Some people think why Ibinder is not returned to the caller during bindService. This is because it is asynchronous when the service is started and cannot be obtained and returned when bindService is called, therefore, you can only throw the IBinder to the onServiceConnected parameter when calling onbind.

5. Some people will encounter onServiceConnected () which is not called after bindService. Check your onBind () function. If the return value is null, The onServiceConnected () callback will not be triggered, therefore, make sure that onBind returns a class that implements the IBinder interface.

6. We can return true in the onUnbind () method. In this case, after we unbind the Service and bind it again, we will call the onRebind () method, which is not very common, instead of onBind ().

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.