"Android" 16.2 Started Services

Source: Internet
Author: User

Category: C #, Android, VS2015;

Date Created: 2016-03-01 I. INTRODUCTION

A Started service is an explicit startup of an object of the same application, or it is started when the device is booted (a condition configured for the service). Ii. life cycle of Started services

As we said earlier, the service is a separate component (for example, detached from an activity) and can be started and stopped by itself. Therefore, whether started services or bound services, these services have their own independent life cycle.

Demonstrates methods that are called during the life cycle of started services.

Once the service is started (started), it has its own life cycle, which is independent of the component that initiated it. And it can keep running in the background, even if the component that started it is destroyed. Therefore, the service should be able to terminate itself after completion of the work, terminate the service itself by calling Stopself (), or terminate the service by calling StopService () by other components.

For application components such as activity, you can start the service by calling StartService () and pass in a intent object that gives the data needed for the service and service. The service will receive the intent object in the Onstartcommand () method. For example, suppose an activity needs to save some data to an online database, and the activity can start a daemon service and send the data to the service by passing in a intent of startservice (), The service receives intent, connects to the Internet, and database transactions within Onstartcommand (). When the transaction is complete, the service terminates itself and is destroyed by the system.

Warning: By default, the process that runs the service is the same as the application and runs in the main thread of the application. Therefore, if your service is performing computationally intensive or blocking operations while the user needs to interact with activity in the same application, the service will degrade the performance of the activity. To avoid the impact on application performance, you should start a new thread in the service.

The most important callback methods to rewrite when using the service are the following.

1, Onstartcommand ()

This method is called by the system when any object requests a service start. For example, when an activity requests a service by calling StartService (), this method is called by the system. Calling StartService (), rebooting the system, and so on will also call the method.

Once this method is executed, the service is started and continues to run in the background. If your code implements this method, you are responsible for terminating the service by calling Stopself () or StopService () after the work is done.

Onstartcommand requires that a value of the Startcommandresult enumeration type be returned, which tells the Android system if the service obtained has stopped if the service should be restarted. For example, the following code returns the Startresultcommand.sticky enumeration value, which automatically restarts the service when the Onstartcommand method is executed:

public override Startcommandresult Onstartcommand (...)

{

Start a task here

......

return startcommandresult.sticky;

}

The Startcommandresult enumeration value can be one of the following options:

    • sticky– This option indicates that the specified service will be restarted and passed to the Onstartcommand method with a value of NULL for the intent type parameter. This service is often used to continuously perform a long-running operation (such as stock quotes).
    • redeliverintent– This option is used when performing a service normally intent contains critical additional information (extra information). If the service is stopped before the last intent is sent, the service is restarted, and the intent is passed to the Onstartcommand method.
    • notsticky– The service does not restart automatically.
    • stickycompatibility– This option is provided only for compatibility with versions prior to API 5 and has the same meaning as sticky, which is rarely used in today's projects.

Of these returned options, the most common is startcommandresult.sticky. Of course, other options will be used in different situations, otherwise there is no point in providing different options.

Note: Android 1.6 and earlier versions use the OnStart () method instead of the Onstartcommand () method. Starting with Android 2.0, OnStart () is obsolete and replaced with Onstartcommand ().

2, Onbind ()

This method is called when other components need to bind the service through Bindservice (), such as RPC execution. In the implementation code of this method, you must return IBinder to provide an interface that the client uses to communicate with the service. You must ensure that this method is implemented, but if you do not need to provide a binding, return null.

3, OnCreate ()

It is called once when the service is first started and is typically used for initialization.

Note This method is called only once for the first time the service is started. If the service is already running, this method is no longer called.

4, OnDestroy ()

The system calls this method when the service is not available and is being destroyed. Your service should use this method to clean up the resources used by the service, such as threads, registered listener listener, receiver receiver, and so on. This will be the last call the service receives.

If a component starts the service by calling StartService () (which causes a call to Onstartcommand ()), the service will remain running until it terminates itself with a stopself () termination or by another component calling StopService ().

If a component calls Bindservice () to create a service (at which point Onstartcommand () is not called), the lifetime of the service is consistent with the component being bound. Once all the clients have unbound the service, the service is destroyed.

The Android system will forcibly terminate a service only if the memory is poor and the system resources of the activity that has the user focus must be overwritten. If the service is bound by an activity that has user focus, it is generally not killed. If the service is declared as "running the service in the foreground", it will almost never be killed. Otherwise, if the service has been started and has been running for a long time, then the system will decrease its level in the background task list over time, and such services will most likely be killed-if the service is already started, you must design the code so that it is perfectly capable of dealing with the system reboot. If the system kills your service, the service will start again (depending on the return value of Onstartcommand (), as long as the resource is again sufficient.)

For more information about when the system might destroy services, see processes and threads. Iii. Create, start, and stop started services

1. Creating a Custom Service

The first step in creating a service is to create a subclass that inherits from service (the service class is the base class for all services).

In contrast to custom activities, the Serviceattribute attribute declaration (when declaring an attribute in C # with the attribute suffix removed and then surrounded by brackets) tells the system that this is a custom service:

[Service]

public class Myservice:service

{

...

}

When the service attribute is declared with the Serviceattribute class, it automatically registers it in the androidmanifest.xml without requiring us to manually configure the Androidmanifest.xml file. For example, assuming that the project name is ServiceDemo1, with a [Service] declaration, it automatically adds the following code to the Androidmanifest.xml:

<service android:name= "Servicedemo1. ServiceDemo1 "></service>

Of course, you can also manually add the configuration code in Androidmanifest.xml, but generally do not (18.1 has been said again), this is because the configuration file is added when there is no smart hints, especially for beginners is more prone to error. When implemented with subclasses that inherit from the service, smart hints are added when adding attributes to the. cs file, which eliminates the hassle of configuration and is very simple, intuitive, and convenient to use.

2. Start Service

Calling the StartService () method in context (for example, an activity) can initialize started Services.

If the service is starting from an activity, you can call the StartService () method directly in the activity, otherwise you can get the current context through Android.App.Application.Context before calling the method.

To start a service, you pass a intent that specifies the type of service to start and the current context.

For example, the following code launches a MyService type of service in an activity:

This. StartService (New Intent (This, typeof (MyService)));

From the started services life cycle we already know that calling the StartService () method will cause Android to invoke the Onstartcommand () method provided in the service. Also know that the Onstartcommand () requirement must return a value of the Startcommandresult enumeration type, which tells the Android system if the obtained service has stopped if the service should be restarted.

For example, the following code returns the Startresultcommand.sticky enumeration value, which automatically restarts the service when the Onstartcommand method is executed:

public override Startcommandresult Onstartcommand (Intent Intent, startcommandflags flags, int startid)

{

Start a task here

New Task (() = {

Long running code

DoWork ();

}). Start ();

return startcommandresult.sticky;

}

Note: In this method, you must use a task or a custom thread to perform the initialization of the service. This is because the service is running on the UI thread, and any long-running tasks will cause the UI render to pause, causing the application to be unresponsive. Using a task or a custom thread to perform the initialization of the service does not cause the interface to pause.

3. Stop Service

Unless the task begins to run indefinitely, a service that has started should call the Stopself method to stop it endlessly running for a long time. This is important because started services is a standalone component that continues to occupy the drawing resources of the system until it is explicitly stopped or shut down by the operating system.

The following code demonstrates how to call the Stopself () method to stop a service after completing a task:

public void DoWork ()

{

var t = new Task (() = {

Thread.Sleep (5000); Simulate long-executing tasks

Stopself ();

});

T.start ();

}

Or:

public void DoWork ()

{

var t = new Thread (() = {

Log.debug ("Demoservice", "Doing work");

Thread.Sleep (5000);

Log.debug ("Demoservice", "Work Complete");

Stopself ();

});

T.start ();

}

In addition, to avoid the possibility of continuing the service indefinitely, the caller can also stop the service by calling the StopService method, as follows:

StopService (New Intent (This, typeof (MyService)));

When the service is stopped, the Started service will automatically invoke the OnDestroy method in the services, in which case the resources used to clean up the service should be done.

In the service class, you only need to override the OnDestroy method:

public override void OnDestroy ()

{

Base. OnDestroy ();

Write code to clean up resources here

}

Multiple callers can request to start the service, and if an external request starts the service, you can also pass Startid to the Onstartcommand method to prevent the service from being prematurely stopped. The startid corresponds to the StartService method of the last call, and the value is incremented each time the Onstartcommand method is executed. Therefore, if the request after StartService has not resulted in a call to Onstartcommand, the service can call the Stopselfresult method and pass the Startid up-to-date value it receives. If the call to Startservic does not cause the Onstartcommand to run, the system does not stop the service because the method used in the Startid call will not correspond to the most recent StartService call.

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 ().

Again: It is important that your application terminates it when the service finishes its work. This avoids the waste of system resources and saves battery power consumption. If necessary, other components can terminate the service by calling StopService (). Even if your service allows binding, you must ensure that it can terminate itself when it receives a call to Onstartcommand ().

The system will destroy the service as soon as the termination request with stopself () or StopService () is issued.

However, if your service is processing multiple onstartcommand () requests at the same time, you should not terminate the service during the process of initiating the request, because you may receive a new boot request (terminating the service after the first request has been processed stops processing of the second request.) To avoid this problem, you can use stopself (int) to ensure that the request to terminate the service is always done based on the most recent boot request. In other words, when you call stopself (int), you pass the start Request ID (Sent to Onstartcommand () Startid) to the corresponding termination request. Thus, if the service receives a new start request when you can call stopself (int), the ID will be different and the service will not be terminated. Iv. Example 1--startedservicedemo1

Run

Main design Steps

(1) Add Ch1601_main.axml

<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"android:orientation= "vertical"Android:layout_width= "Fill_parent"Android:layout_height= "Fill_parent">  <ButtonAndroid:id= "@+id/ch1601startservice"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:text= "Start Service" />  <ButtonAndroid:id= "@+id/ch1601stopservice"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"Android:text= "Stop Service" /></LinearLayout>

(2) Add Ch1601ServiceDemo.cs

usingAndroid.app;usingandroid.content;usingAndroid.os;usingAndroid.runtime;usingAndroid.widget;usingSystem.Threading;namespacemydemos.srcdemos{[Service] Public classch1601servicedemo:service {thread thread; [return: Generatedenum] Public OverrideStartcommandresult Onstartcommand (Intent Intent, [generatedenum] startcommandflags flags,intStartid) {            //after you get the message loop for the main thread, you can display messages from the service in the main thread.            varMyHandler =NewHandler (Mainlooper); //perform a service here that takes a long time to processThread =NewThread (() =            {                //Process , you can also tell the user the status of processing//This is used to simulate a message every 3 seconds, and this service can be terminated at any time by mainactivity                 for(inti =1; I <=Ten; i++)                {                    varmsg =string. Format ("This is the first {0} message from the service", i); Thread.Sleep ( the); Myhandler.post (()={Toast.maketext ( This, MSG, Toastlength.long).                    Show ();                });            } stopself ();            }); Thread.            Start (); returnStartcommandresult.notsticky; }         Public Override voidOnDestroy () {Base.            OnDestroy (); Thread.            Abort (); varMyHandler =NewHandler (Mainlooper); Myhandler.post (()={Toast.maketext ( This,"service is stopped", Toastlength.long).            Show ();        }); }        //interfaces that the base class requires to implement         Public Overrideibinder onbind (Intent Intent) {return NULL; }    }}

Note that if you find that Chinese is garbled in the run, do not forget that you need to specify the regional language in the AssemblyInfo.cs file (as described in the previous section), modify the following statement (specify "ZH-CN" in the parameter):

[Assembly:assemblyculture ("ZH-CN")]

What's on the Internet how to change the advanced save options are digging holes, don't believe it.

(3) Add Ch1601MainActivity.cs

usingAndroid.app;usingandroid.content;usingAndroid.os;usingAndroid.widget;namespacemydemos.srcdemos{[Activity (Label="ch1601mainactivity")]     Public classch1601mainactivity:activity {protected Override voidOnCreate (Bundle savedinstancestate) {Base.            OnCreate (savedinstancestate);            Setcontentview (Resource.Layout.ch1601_Main); Intent Intent=NewIntent ( This,typeof(Ch1601servicedemo)); varStart = findviewbyid<button>(Resource.Id.ch1601StartService); Start. Click+=Delegate{StartService (intent); Toast.maketext ( This,"The service has been started! ", Toastlength.short).            Show ();            }; varStop = findviewbyid<button>(Resource.Id.ch1601StopService); Stop. Click+=Delegate{StopService (intent); Toast.maketext ( This,"The service was forcibly requested to stop! ", Toastlength.short).            Show ();        }; }    }}

"Android" 16.2 Started Services

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.