Android Create services started service detailed introduction _android

Source: Internet
Author: User
Tags gettext

Create started Service

An application component (for example, an activity) invokes StartService () to start a service, passing the required parameters through intent to Service,service will get intent in the Onstartcommand function.

There are two ways to create started service, one is to extend the service class, the other is to extend the Intentservice class

Extended Service
This is the base class for all services. When extending this class, it is particularly important to create a new thread to do the service task, because it is running on your main thread (UI thread), which makes your main thread run slowly.

Extended Intentservice
This is a subclass of a service that can handle all the startup requests in a worker thread. If you don't need all the service requests at the same time, using Intentservice is a good choice. All you need to do is implement the Onhandlerintent () method, which handles every initiation request that you accept.


Here we learn how to extend the Intentservice class and service class

Extended Intentservice Class

What did Intentservice do?
1. Create a worker thread that is independent of the main thread to perform all the intent that came through Onstartcommand ().
2. Create a Task force column that will pass all the accepted intent to onhandlerintent (), so at the same time you only deal with a intent, don't worry about multithreading problems.
3. When all requests are processed, stop the service, so you do not need to manually invoke Stopself ().
4. Provide the default implementation of the Onbind () function, return null
5. Provide the default implementation of the Onstartcommand () function, which sends the intent to the work queue, and then the work queue is sent to your onhandlerintent () function.

With the above foundation, all you have to do is implement Onhandlerintent (). and implement a small constructor.

Refer to the following example:

Copy Code code as follows:

public class Hellointentservice extends Intentservice {

/**
* A constructor is required, and must call the Super Intentservice (String)
* Constructor with a name for the worker thread.
*/
Public Hellointentservice () {
Super ("Hellointentservice");
}

/**
* The Intentservice calls this is the default worker thread with
* The intent that started the service. When this method returns, Intentservice
* Stops the service, as appropriate.
*/
@Override
protected void Onhandleintent (Intent Intent) {
Normally we would do some work here, like download a file.
For our sample, we are just for 5 seconds.
Long endtime = System.currenttimemillis () + 5*1000;
while (System.currenttimemillis () < Endtime) {
Synchronized (this) {
try {
Wait (Endtime-system.currenttimemillis ());
catch (Exception e) {
}
}
}
}
}

If you want to implement other callback functions, such as OnCreate, Onstartcommand, OnDestroy must remember to invoke the corresponding function of the parent class, so that Intentservice can handle the worker thread correctly.

For example, you need to pop a hint in the Onstartcommand function, so you can write:

Copy Code code as follows:

@Override
public int Onstartcommand (Intent Intent, int flags, int startid) {
Toast.maketext (This, "service starting", Toast.length_short). Show ();
Return Super.onstartcommand (Intent,flags,startid);
}

One exception is that if you need other component binding services, then your onbind function does not need to invoke the onbind of the parent class.

In the next section, you'll see that by extending the service class to achieve the same services as this section, the difference is that the code will be more, but it also means more flexibility, especially if you need to process multiple requests at the same time, it is more appropriate to extend the service directly.

Extended service class

As you can see in the previous section, using Intentservice to implement a started service is simple. If you need your service to execute multiple threads, then you need to extend the service class to handle each intent.

As a contrast, the following example uses the service class to implement the same functionality as in the previous section.

Copy Code code as follows:

public class HelloService extends Service {
Private Looper Mservicelooper;
Private Servicehandler Mservicehandler;

Handler that receives messages from the thread
Private Final class Servicehandler extends Handler {
Public Servicehandler (Looper looper) {
Super (Looper);
}
@Override
public void Handlemessage (msg) {
Normally we would do some work here, like download a file.
For our sample, we are just for 5 seconds.
Long endtime = System.currenttimemillis () + 5*1000;
while (System.currenttimemillis () < Endtime) {
Synchronized (this) {
try {
Wait (Endtime-system.currenttimemillis ());
catch (Exception e) {
}
}
}
Stop the service using the Startid, so we don ' t stop
The service in the middle of handling another job
Stopself (MSG.ARG1);
}
}

@Override
public void OnCreate () {
Start up the thread running the service. Note that we create a
Separate thread because the service normally runs in the process ' s
Main thread, which we don ' t want to block. We also make it
Background priority so cpu-intensive work won't be disrupt our UI.
Handlerthread thread = new Handlerthread ("Servicestartarguments",
Process.thread_priority_background);
Thread.Start ();

Get the Handlerthread ' s looper with it for our Handler
Mservicelooper = Thread.getlooper ();
Mservicehandler = new Servicehandler (mservicelooper);
}

@Override
public int Onstartcommand (Intent Intent, int flags, int startid) {
Toast.maketext (This, "service starting", Toast.length_short). Show ();

For each start request, send a message to start a job and deliver the
Start ID so we know which request we ' re stopping when we finish the job
Message msg = Mservicehandler.obtainmessage ();
MSG.ARG1 = Startid;
Mservicehandler.sendmessage (msg);

If we have killed, after returning from here, restart
return start_sticky;
}

@Override
Public IBinder Onbind (Intent Intent) {
We don ' t provide binding, so return null
return null;
}

@Override
public void OnDestroy () {
Toast.maketext (this, ' service done ', Toast.length_short). Show ();
}
}

As you can see, there's a lot more code than the Intentservice example.

You can process multiple requests at the same time because you handle each onstartcommand () yourself. This example does not do this, but if you do, you can simply create a new thread every time you receive a request and run it immediately, rather than wait until the last request processing is complete.

Note that the Onstartcommand () function must return an integer. This integer describes how the service will be processed when the system kills the service. The return value must be the following values:
Start_not_sticky
After the Onstartcommand () return, the system kills the service and the service will not reboot unless there is a pending intents (currently I do not know what is pending intents) to deliver. This is a good place to restart unfinished tasks very easily.

Start_sticky
After the system kills the service, restart the service and Invoke Onstartcommand (), but do not post the last intent. The system passes to the Onstartcommand () function null unless there is a pending intent to start the service, which is passed to Onstartcommand () corresponding intent. This approach is more suitable for media playback services, do not need to execute commands, but run independently, often in waiting for the task of the service.

Start_redeliver_intent
After the system kills the service, the service is restarted and the Onstartcommand () is invoked, the parameters are passed to the previous intent, and then the pending intent incoming Onstartcommand () is followed. This is ideal for performing a task that cannot be immediately restored, such as downloading files.

Start Service

You can start a service by invoking StartService (intent) from an activity or other component. The Android system invokes the Onstartcommand () function of the service and passes it intent.

Use the HelloService in the previous section to make an example:
Intent Intent = new Intent (this, helloservice.class);
StartService (Intent);
StartService () will return immediately, and the Android system will invoke the Onstartcommand () function of the service. If this is the service is not running, the system first calls the OnCreate () function, and then the Onstartcommand () function is called immediately thereafter.

If the service does not provide bindings, the intent passed in by the StartService () function is the only way to interact with the application components and services. If you want the service to send the results to the customer component, the customer component needs to create a pendingintent for the broadcast and deliver it to the service via intent when the service is started. In this way, the service can use the broadcast to send the results to the customer component.

Multiple requests can cause the service's Onstartcommand () to be invoked multiple times. However, only one stop request (Stopself () or StopService ()) will cause the service to stop.

Stop Service

A service that starts must manage its own lifecycle. Because the system does not stop or destroy services unless the system needs to recycle resources. Therefore, the service must stop itself by calling Stopself () or another component call StopService ().

Upon receipt of a stop request from stopself () or StopService (), the system will destroy the service immediately.

If your service handles multiple service requests at the same time, the service cannot be stopped immediately when a request completes, because you may have accepted a new request (ending the service at the end of the first request terminates the second request). To solve this problem, you can call the stopself (int) function to ensure that your stop request is always based on the most recent service request. This is because the call to the stopself (int) function
Passes the Onstartcommand () function incoming Startid to the stop request. The service does not end when your Startid and last received service request do not match.

Note: the stopself (int) function is simply compared with the last received Startid, if your service processing is multi-threaded, the service request may be received after the first completion, then the stopself (int) scheme is not suitable for you, You should manually manage the service requests and services that you receive, such as recording the Startid in a table in the Onstartcommand () function, recording the completion status in the table when the service task is completed, and directly calling Stopself () when the tasks in the table are complete. To stop the service.

Running services at the front desk

A front desk service is a service that users can be aware of, and when available memory is low, the system does not kill the front desk service. A foreground service must provide a status bar notification, which is placed in the running entry, which means that the notice will not disappear as long as the service is not stopped or is always the front desk service.

For example, a music player service should be set up for the foreground to run because the user is obviously aware that he is running. This status bar notifies you of the songs that are playing and allows users to click into the music playback interface.

To make a service run at the foreground, simply call Startforeground (). This method has two parameters: an integer ID for the notification and a status bar notification. Code fragment:

Copy Code code as follows:

Notification Notification = new Notification (R.drawable.icon, GetText (R.string.ticker_text),
System.currenttimemillis ());
Intent notificationintent = new Intent (this, exampleactivity.class);
Pendingintent pendingintent = pendingintent.getactivity (this, 0, notificationintent, 0);
Notification.setlatesteventinfo (This, GetText (R.string.notification_title),
GetText (r.string.notification_message), pendingintent);
Startforeground (ongoing_notification_id, NOTIFICATION);

Use the Stopforeground () function to remove a service from the foreground. This function takes a Boolean parameter to indicate whether to remove the notification from the status bar. This function does not stop the service. If the front desk service is stopped, the notification will be removed as well.

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.