Fourth three cornerstones of Android development-activity, service and handler (4)

Source: Internet
Author: User

4.2 Ever-changing service-service development

The service is an Android system that runs in the background, and does not interact with the user application component. It is similar to the activity level and can only be run in the background. Each service must be declared in the manifest file by <service>.

The life cycle of the 4.2.1 service

The service life cycle is not as complex as activity, it inherits only the OnCreate (), OnStart (), OnDestroy () three methods, and when we first start the service, we call OnCreate (), OnStart () These two methods, when the service is stopped, the execution of the OnDestroy () method, it is important to note that if the service has been started, when we start the service again, no longer execute the OnCreate () method, Instead, the OnStart () method is executed directly. Service launches have StartService and Bindservice two methods that have different effects on the service life cycle.

Let's look at how these two approaches affect the service life cycle, respectively:

1) startservice Start service

Starting service,service in this way will go through onCreate and then OnStart, and then be in the running state until StopService calls the OnDestroy method. If the caller exits directly without calling StopService, the service will run in the background.

2) bindservice Start service

Starting service,service in this way will run OnCreate, and then call Onbind, at which point the caller and the service are bound together. When the caller exits, Srevice calls the Onunbind->ondestroyed method. The so-called binding together is a common survival. The caller can also stop the service by calling the Unbindservice method, when Srevice calls the Onunbindonunbind->ondestroyed method.

4.2.2 Service start-up and stop

We have a certain understanding of the service life cycle, the service is started differently, and its life cycle is not the same. Below, let's look at how the service starts and stops.

The service cannot run itself and needs to start the service by calling the Context.startservice () or Context.bindservice () method. Both of these methods can start the service, but they are used in different situations.

1) The service is enabled with the StartService () method, the caller is not connected to the service, and the service is still running even if the caller exits.

If you plan to start the service with the Context.startservice () method, the system calls the service's OnCreate () method first, and then calls the OnStart () method when the service is not created.

If the StartService () method is called before the service has been created, calling the StartService () method multiple times does not cause the service to be created more than once, but results in multiple calls to the OnStart () method.

Services started with the StartService () method can only call the Context.stopservice () method to end the service, and the OnDestroy () method is called at the end of the service.

2) using the Bindservice () method to enable the service, the caller and the service are bound together, once the caller exits, the service terminates, there is a "do not ask for the same life, must die" characteristics.

Onbind () The method is only invoked when the service is started with the Context.bindservice () method. This method is called when the caller and the service are bound, and the Context.bindservice () method is called multiple times when the caller is tied to the service and does not cause the method to be called more than once.

Using the Context.bindservice () method to start a service can only call the Onunbind () method to disassociate the caller from the service and call the OnDestroy () method at the end of the service.

4.2.3 my service.-Local Service (Localservice) development

The local service is used inside the application. It can start and run until someone stops it or it stops itself. In this way, it starts with calling Context.startservice () and calls Context.stopservice () to stop. It can also call service.stopself () or Service.stopselfresult () to stop itself. No matter how many times the StartService () method is called, you only need to call StopService () once to stop the service.

It is used to implement some of the application's own time-consuming tasks, such as query upgrade information, it does not occupy the application activity belongs to the thread, but only a single-threaded background execution, so the user experience is better.

Some services do not need to interact with the activity to run directly, while others need to interact with the activity. Let's take a few examples to illustrate this.

--------------------------------------------trying to put an ad, and now there's no work to survive.Ping An Lufax is affiliated to the Ping An group's peer platformannual ROI 7%-9% is the preferred alternative to bank bankingPersonal lessons recommend investing in anxin or guaranteed rainbow projectsdon't invest in an e that's almost impossible to transfer it's very difficult to withdraw in advanceRegistration LinkHttp://affiliate.lufax.com/action/36XBUSign up with this link and I'll have dozens of bucks for the extra cash bonus.--------------------------------------------

1) Local services that do not interact with the activity

First, we create a new LocalService class that inherits from the service, with the following code:

Import slightly

public class LocalService extends service{

@Override

Public IBinder Onbind (Intent Intent) {

return null;

}

@Override

public void OnCreate () {

Super.oncreate ();

}

@Override

public void OnDestroy () {

Super.ondestroy ();

}

@Override

public void OnStart (Intent Intent, int startid) {

Super.onstart (Intent, Startid);

}

}

Then, create a new class serviceactivity inherits from Actvity, the code is as follows:

Import slightly

public class Serviceactivity extends activity{

Private Button startbtn,stopbtn;

@Override

protected void OnCreate (Bundle savedinstancestate) {

Super.oncreate (savedinstancestate);

Setcontentview (R.layout.localservice);

STARTBTN = (Button) Findviewbyid (R.id.start_button);

STOPBTN = (Button) Findviewbyid (R.id.stop_button);

Startbtn.setonclicklistener (New View.onclicklistener () {

@Override

public void OnClick (View v) {

StartService (New Intent ("Com.char4.LOCAL_SERVICE"));

}

});

Stopbtn.setonclicklistener (New View.onclicklistener () {

@Override

public void OnClick (View v) {

StopService (New Intent ("Com.char4.LOCAL_SERVICE"));

}

});

}

}

The layout file Localservice.xml code is as follows, it defines two buttons, one to start the service, and one to stop the service:

<?xml version= "1.0" encoding= "Utf-8"?>

<linearlayout

Xmlns:android= "Http://schemas.android.com/apk/res/android"

android:orientation= "Horizontal"

Android:layout_width= "Match_parent"

android:layout_height= "Match_parent" >

<button

Android:id= "@+id/start_button"

Android:layout_width= "Wrap_content"

android:layout_height= "Wrap_content"

android:text= "Start"/>

<button

Android:id= "@+id/stop_button"

Android:layout_width= "Wrap_content"

android:layout_height= "Wrap_content"

android:text= "Stop"/>

</LinearLayout>

Don't forget to sign up for service in Androidmainfest.xml:

<service android:name= ". LocalService ">

<intent-filter>

<action android:name= "Com.char4.LOCAL_SERVICE"/>

<category android:name= "Android.intent.category.default"/>

</intent-filter>

</service>

Below, let's look at the effect, shown in 4-7:

Figure 4-7 StartService Boot order

Through log printing we can find that the first time you click on the "Start" button, the OnCreate and OnStart methods are called, and no matter how many times the "Start" button is clicked, the OnStart is only called until the "Stop" button is clicked. The OnDestroy is called when the Stop button is clicked. Clicking the "Stop" button again will reveal that it will not enter the service life cycle, i.e. no more calls to Oncreate,onstart and OnDestroy, and Onbind is not invoked when the "start" and "Stop" buttons are clicked.

Fourth three cornerstones of Android development-activity, service and handler (4)

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.