Android: Basic usage of the service

Source: Internet
Author: User

9.3 Basic usage of the service

After understanding the technology of Android multithreaded programming, let's go to the topic of this chapter and start learning about the content of the service. As one of the four components of Android, the service also has a lot of very important points of knowledge, we naturally have to start from the most basic use of learning.

9.3.1 Define a service

First look at how to define a service in your project. Create a new Servicetest project, and then add a class named MyService to this project, and let it inherit from the Service, and the finished code looks like this:

public class MyService extends Service {

@Override

Public IBinder Onbind (Intent Intent) {

return null;

}

}

At present MyService can be considered empty, but there is a onbind () method is particularly eye-catching. This method is the only abstract method in the Service, so it must be implemented in subclasses. We'll use the Onbind () method in a later section, which we can now temporarily ignore.

Since the definition of a service, nature should be in the service to deal with some things, the logic to deal with things should be written where? You can then rewrite some of the other methods in the Service as follows:

public class MyService extends Service {

@Override

Public IBinder Onbind (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 ();

}

}

As you can see, here we rewrite the three methods of OnCreate (), Onstartcommand () and OnDestroy (), which are the three most commonly used methods in each service. where the OnCreate () method is called when the service is created, the Onstartcommand () method is invoked every time the service is started, and the OnDestroy () method is called when the service is destroyed.

Normally, if we want the service to execute an action as soon as it is started, we can write the logic in the Onstartcommand () method. And when the service is destroyed, we should reclaim those resources that are no longer used in the OnDestroy () method.

Also need to note that each service needs to be registered in the Androidmanifest.xml file in order to take effect, do not know if you have found that this is the four components of Android common features. So we should also repair the Androidmanifest.xml file, the code is as follows:

<manifestxmlns:android= "Http://schemas.android.com/apk/res/android" package= "Com.example.servicetest"

Android:versioncode= "1" android:versionname= "1.0" >

......

<applicationandroid:allowbackup= "true" android:icon= "@drawable/ic_launcher" android:label= "@string/app_name" Android:theme= "@style/apptheme" >

......

<service android:name= ". MyService ">

</service>

</application>

</manifest>

In this case, a service has been fully defined.

9.3.2 Start and stop services

Once you have defined the service, you should consider how to start and stop the service. Starting and Stopping methods of course you will not be unfamiliar, mainly through the use of Intent to achieve, let us in the Servicetest project to try to start and stop myservice this service.

First modify the code in the Activity_main.xml as follows:

<linearlayoutxmlns:android= "Http://schemas.android.com/apk/res/android" android:layout_width= "match_parent" android:layout_height= "Match_parent "

android:orientation= "Vertical" >

<buttonandroid:id= "@+id/start_service" android:layout_width= "match_parent" android:layout_height= "Wrap_ Content "android:text=" Start Service "/>

<buttonandroid:id= "@+id/stop_service" android:layout_width= "match_parent" android:layout_height= "wrap_content "android:text=" StopService "/>

</LinearLayout>

Here we have added two buttons to the layout file, which are used to start the service and stop the service. Then modify the code in the mainactivity as follows:

public class Mainactivity extends Activity implementsonclicklistener {

Private Button StartService;

Private Button StopService;

@Override

Protected voidoncreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main);

StartService = (Button) Findviewbyid (R.id.start_service);

StopService = (Button) Findviewbyid (R.id.stop_service);

Startservice.setonclicklistener (this);

Stopservice.setonclicklistener (this);

}

@Override

public void OnClick (VIEWV) {

Switch (V.getid ()) {

Case R.id.start_service:

Intent startintent = new Intent (this, myservice.class);

StartService (startintent);//Start- up service

Break

Case R.id.stop_service:

Intent stopintent = new Intent (this, myservice.class);

StopService (stopintent);// Stop Service

Break

Default

Break

}

}

}

As you can see, there are instances of the Start service button and the Stop service button are obtained in the OnCreate () method, and the click events are registered with them. Then, in the Click event of the Start Service button, we built a Intent object and called the StartService () method to start the MyService service. In the Click event of the Stop Serivce button, we also built a Intent object and called the StopService () method to stop myservice the service. Both the StartService () and the StopService () methods are defined in the Context class, so we can invoke both methods directly in the activity. Note that it is entirely up to the activity to determine when the service is stopped, and if you do not click the Stop Service button, the service will remain in the running state. Is there any way for the service to stop itself? Of course, you just have to call the Stopself () method at any point in the MyService to stop the service.

Then there is another problem to think about, how can we verify that the service has been successfully started or stopped? The simplest approach is to include the print log in several methods of MyService, as follows:

public class MyService extends Service {

@Override

Public IBinder Onbind (Intent Intent) {

return null;

}

@Override

public void OnCreate () {

Super.oncreate ();

LOG.D ("MyService", "OnCreate executed");

}

@Override

public int Onstartcommand (Intent Intent, int flags, int startid) {

LOG.D ("MyService", "onstartcommandexecuted");

Return Super.onstartcommand (Intent, flags, Startid);

}

@Override

public void OnDestroy () {

Super.ondestroy ();

LOG.D ("MyService", "OnDestroy executed");

}

}

You can now run the program to test it, as shown in the main interface 9.5 of the program.

Figure 9.5

Click on the Start Service button to observe print log 9.6 in LogCat.

Figure 9.6

The OnCreate () and Onstartcommand () methods in MyService are executed, indicating that the service has actually started successfully, and you can find it in the list of running services, as shown in 9.7.

Figure 9.7

Then click on the Stop Service button and observe print log 9.8 in LogCat.

Figure 9.8

This proves that the MyService has indeed stopped successfully.

Anyway, although we have learned to start the service and stop the service method, do not know your heart now have a doubt, that is onCreate () method and Onstartcommand () What is the difference? Because just click

Both methods are executed after the Start Service button.

In fact, the OnCreate () method is called at the time the service was first created, and the Onstartcommand () method is called every time the service is started, since we were first clicked on the Start Service button and the service was not created at this time. So all two methods are executed, and then if you click the Start Service button several times in a row, you will find that only the Onstartcommand () method can be executed.

Android: Basic usage of the service

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.