Android Learning Note (51): Services Service (UP)-Intentservice

Source: Internet
Author: User

For long-term operations, such as playing music, long-term, and server connections, the service is used even if the current activity of the screen is not still needed to run. The service will trigger startup via API triggering or trigger via IPC (interprocess communication) connection request. The service will run until it is shut down, or the system shuts down when there is not enough memory. In general, to conserve power, services should be optimized to reduce CPU consumption and large amounts of network traffic. Services can be used in the following scenarios:

1, the user left the activity, still need to continue to work, such as downloading files from the network, playing music
2, whether the activity appears (reproduce) or leave, need to continue to work, such as Web chat application
3. Connecting to a network service, using a service provided by a remote API
4, timed triggered services, such as Cron in Linux.

Declaring a service in manifest

As with activity, content provider, the service must also be declared in the Androidmanifest file as a child node in <application>. Example of our first service below is Servicedownloader.

<application. >
... ...
<service android:name= ". Servicedownloader ">
</application >

Command mode: Intentservice

Writing your own service inherits the service class of Android, or the subclass of the service Intentservice. There are two ways to trigger a service, one is to send a command, that is, the command pattern of this learning, a binding service, and a two-way communication channel between services. The command mode example is the HTTP remote download file service.

Service Servicedownloader

/ * Command mode service is requested by client, service is processed, and the service is closed after completion, the client does not need to care whether or not to end the service, suitable for one-time processing, such as this example * /
public class Servicedownloaderextends Intentservice{
Private HttpClient client = null;

Public Servicedownloader () {
Super ("Servicedownloader");
}
When the client requests the service through StartService (), if the service is not turned on, the OnCreate () is executed first, and we do the initialization of the service here, note that onCreate () is running in the main thread.
public void OnCreate ()
{
Super.oncreate ();
Client = new Defaulthttpclient ();
}
//If the client issues StartService (), if the service is not turned on, the service OnCreate () is turned on first, after the service is turned on, or if the service is turned on, Onstartcommand () is triggered, note that this is also running in the main thread, We do not apply to place some time-long processing here. In general, the initialization of this service can be done based on the commands received. In principle, because it is the main thread, the UI can be manipulated, but the good programming style, the service does not process the content of the activity.
public int Onstartcommand (Intent Intent, int flags, int startid) {

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

//This is the method that must be override, executed after receiving the client command, processing Onstartcommand (), note that Onhandlerintent is running in a background thread and should place the main processing content here
protected void Onhandleintent (Intent i) {
/*http's example has been learned before, the first is to get the remote file using the Get method. The returned HTTP is stored in the ResponseHandler, we write a private class Bytearrayresponsehandler to handle, check the return value of HTTP, if not a total OK, such as 3xx-6xx, it indicates an exception, such as success, Store the acquired content in a file. */
HttpGet GetMethod = new HttpGet (I.getdata (). toString ());
try{
responsehandler<byte[]> ResponseHandler = new Bytearrayresponsehandler ();
byte[] Responsebody =Client.execute(Getmethod,responsehandler);
File output = new file (Environment.getexternalstoragedirectory (),
I.getdata (). Getlastpathsegment ());
if (output.exists ()) {
Output.delete ();
}
FileOutputStream fos = new FileOutputStream (Output.getpath ());
Fos.write (responsebody);
Fos.close ();
}catch (Exception e) {
LOG.E (GetClass (). GetName (), "Exception:" + e.tostring ());
}
}

If the client issues a StopService () request to stop the service, or the service itself is required to stop the service through Stopself (), the OnDestroy () is triggered, and OnDestroy is also running in the main thread, where we should work to stop the service. If this is the main thread executing onstartcommand (), you must wait for the contents of Onstartcommand () to execute until the contents of OnDestroy () are executed sequentially. If the background thread onhandleintent () is executing at this point, OnDestroy () does not automatically stop the background thread and the background thread continues to run, and we must end the running of the background thread in the Code of OnDestroy (). such as a status check, or a direct shutdown of the connection in the local, interrupt communication
public void OnDestroy ()
{
Client.getconnectionmanager (). Shutdown ();
Super.ondestroy ();
}

The return value returned by the HTTP response is checked, and if it is 3xx-6xx, not 2xx, an error is indicated, such as 404,not Found.
Private class Bytearrayresponsehandler implements responsehandler<byte[]>{
Public byte[] Handleresponse (HttpResponse response) throws Clientprotocolexception, IOException {
Statusline statusline = Response.getstatusline ();
if (Statusline.getstatuscode () >= 300) {
throw new Httpresponseexception (Statusline.getstatuscode (), statusline.getreasonphrase ());
}
httpentity entity = response.getentity ();
if (entity = = null)
return null;
return Entityutils.tobytearray (entity);
}
}
}

Client for Command mode service

/ * The client triggers the service in the command mode, which is only triggered by the StartService () command because the Intentservice is automatically closed after execution */
public class ServiceTest1 extends activity{
... ...
//Tune up the service and the activity is very similar, all through the intent to pass through the SetData pass the parameters, in this case is the direct HTTP URI address.
private void Startdownloader () {
IntentIntent = new Intent (This,servicedownloader.class);
Intent.setdata
(Uri.parse ("http://commonsware.com/Android/excerpt.pdf"));
StartService (intent);
}
//General Command mode service, no need to consider terminating the service. This is only for trial use here. Note that terminating the service terminates the entire service, triggers OnDestroy () in the service, and if the queue has other commands, such as service processing, it will be stopped by the code in OnDestroy (). So the impact is all being and waiting for service processing, not just the client's request, this requires special attention!!
private void Stopdownloader () {
StopService(New Intent (This,servicedownloader.class);
}
}

Communication between the service and the client

In the example above, we want the service to be able to notify the client when it is finished downloading. For command mode services, Messenger can be used to send messages to the activity's handler, which has been learned in thread [study notes (31)].

The client code is as follows

public class ServiceTest1 extends activity{
... ...
private void Startdownloader () {
......
Intent = new Intent (This,servicedownloader.class);
Intent.setdata (Uri.parse ("http://commonsware.com/Android/excerpt.pdf"));
//activity When the service is tuned, that is, StartService () or bindservice () can carry Messenger as the extra pass of the intent, which can be delivered via messenger between the service and the client
Intent.putextra (Servicedownloader.extra_messager,new Messenger (handler));
StartService (Intent);
}
Handler accepts messages through Handlermessage (), runs on the main thread, and handles content such as UI.
Private Handler Handler = new Handler () {
public void Handlemessage (Message msg) {
Super.handlemessage (msg);
Buttonstart.setenabled (TRUE);
Buttonstop.setenabled (FALSE);
Switch (MSG.ARG1) {
Case ACTIVITY.RESULT_OK:
Toast.maketext (Servicetest1.this, "Result:ok", Toast.length_long). Show ();
Break
Case activity.result_canceled:
Toast.maketext (Servicetest1.this, "Result:cancel", Toast.length_long). Show ();
Break
Default
Break
}
}
};
}

The service-side code is as follows:

//Avoid naming duplicates, add the namespace of the class to the front
public static final String extra_messager= "Com.wei.android.learning.ServiceDownloader.EXTRA_MESSAGER";

protected void Onhandleintent (Intent i) {
int result = Activity.result_canceled
Download file processing, success, set RESULT = ACTIVITY.RESULT_OK;
... ...
//Step 1: Get Messenger from Intent's extras
Bundle extras = I.getextras ();

if (extras! = null) {
Messenger Mesenger = (Messenger) extras.get (Extra_messager);
//Step 2: Use Message.obtain () to get an empty message object
Message msg =Message.obtain( );
//Step 3: Fill in message information.
MSG.ARG1 = result;
//Step 4: Send the message out via Messenger Messenger.
try{
mesenger.send (msg);
}catch (Exception e) {
LOG.W (GetClass (). GetName (), "Exception Message:" + e.tostring ());
}
}
}

RELATED Links: My Android development related articles

Android Learning Note (51): Services Service (UP)-Intentservice

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.