Android Intentservice completely parse when service encounters handler

Source: Internet
Author: User

Reprint please indicate the source:
http://blog.csdn.net/lmj623565791/article/details/47143563;
This article is from: "Zhang Hongyang's Blog"

An overview

We all know. In the development of Android, any time-consuming operation will be given to the service as much as possible. For example, if we upload more than one diagram, the upload process user may put the app in the background. And then we do something else, our activity is very likely to be killed, so we can consider the upload operation to the service to do, assuming that the service is killed, but also by setting startForeground(int, Notification) the method to improve its priority.

Then, in the service we certainly cannot take the time-consuming operation directly. It is generally necessary to open a sub-thread to do something, to manage the service life cycle and sub-threading itself is not an elegant approach. Fortunately, Android provides us with a class. Called IntentService . We look at the gaze.

Intentservice is a base class for {@link service}s that handle asynchronous
Requests (expressed as {@link intent}s) on demand. Clients send requests
Through {@link android.content.context#startservice (Intent)} calls; The
Service is started as needed, handles each Intent in turn using a worker
Thread, and stops itself when the it runs out of the work.

Meaning that Intentservice is a service-based class. The request to handle the asynchronous.

You can submit a request through StartService (Intent). The service is created when it is needed, closes itself after all the tasks have been completed, and the request is processed by the worker thread.

That said, we used intentservice at least two of the advantages. On the one hand, there is no need to go to new thread, and there is no need to consider when to close the service.

All right. So let's look at a complete example.

The use of two Intentservice

We'll show you a case of uploading multiple images. Of course we will simulate the time-consuming of uploading, after all, our focus is on the use of Intentservice and source code parsing.

First Look at the

Whenever we click a button. A task will be handed over to the backend service to process, the backend service every processing completed a request will be fed back to the activity, and then the activity to update the UI. When all of the tasks are complete, the backend service exits, and no memory is occupied.

Service

Package Com.zhy.blogcodes.intentservice;import Android.app.intentservice;import Android.content.context;import Android.content.intent;import Android.util.log;public class Uploadimgservice extends intentservice{private static fin    Al String action_upload_img = "Com.zhy.blogcodes.intentservice.action.UPLOAD_IMAGE";    public static final String Extra_img_path = "Com.zhy.blogcodes.intentservice.extra.IMG_PATH"; public static void Startuploadimg (context context, String path) {Intent Intent = new Intent (context, Uploadimgs        Ervice.class);        Intent.setaction (ACTION_UPLOAD_IMG);        Intent.putextra (Extra_img_path, PATH);    Context.startservice (Intent);    } public Uploadimgservice () {Super ("Uploadimgservice"); } @Override protected void Onhandleintent (Intent Intent) {if (Intent! = null) {final S            Tring action = Intent.getaction (); if (Action_upload_img.equals (ACTION)) {final STRing path = Intent.getstringextra (Extra_img_path);            Handleuploadimg (path); }}} private void Handleuploadimg (String path) {try {//Analog upload time Threa            D.sleep (3000);            Intent Intent = new Intent (Intentserviceactivity.upload_result);            Intent.putextra (Extra_img_path, PATH);        Sendbroadcast (Intent);        } catch (Interruptedexception e) {e.printstacktrace ();        }} @Override public void OnCreate () {super.oncreate ();    LOG.E ("TAG", "onCreate");        } @Override public void OnDestroy () {Super.ondestroy ();    LOG.E ("TAG", "OnDestroy"); }}

The code is very short. is mainly inherited IntentService , and then the replication Onhandleintent method, according to the incoming intent to select the detailed operation. startUploadImgI wrote an auxiliary method, save every time to build Intent,startservice.

Activity

Package Com.zhy.blogcodes.intentservice;import Android.content.broadcastreceiver;import Android.content.Context; Import Android.content.intent;import Android.content.intentfilter;import Android.os.bundle;import Android.support.v7.app.appcompatactivity;import Android.view.menu;import Android.view.menuitem;import Android.view.view;import Android.widget.linearlayout;import Android.widget.textview;import Com.zhy.blogcodes.R; public class Intentserviceactivity extends appcompatactivity{public static final String Upload_result = "COM.ZHY.BLOGC    Odes.intentservice.UPLOAD_RESULT ";    Private LinearLayout Mlytaskcontainer; Private Broadcastreceiver Uploadimgreceiver = new Broadcastreceiver () {@Override public void onreceive (C Ontext context, Intent Intent) {if (intent.getaction () = = Upload_result) {St                Ring Path = Intent.getstringextra (Uploadimgservice.extra_img_path);            Handleresult (path); }        }    };   private void Handleresult (String path) {TextView TV = (TextView) mlytaskcontainer.findviewwithtag (path);    Tv.settext (path + "Upload success ~ ~ ~");        } @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_intent_service);        Mlytaskcontainer = (linearlayout) Findviewbyid (R.id.id_ll_taskcontainer);    Registerreceiver ();        } private void Registerreceiver () {intentfilter filter = new Intentfilter ();        Filter.addaction (Upload_result);    Registerreceiver (uploadimgreceiver, filter);    } int i = 0;        public void AddTask (view view) {///analog path String path = "/sdcard/imgs/" + (++i) + ". png";        Uploadimgservice.startuploadimg (this, path);        TextView TV = new TextView (this);        Mlytaskcontainer.addview (TV);        Tv.settext (path + "is uploading ...");    Tv.settag (path); } @Override protected VOID OnDestroy () {Super.ondestroy ();    Unregisterreceiver (Uploadimgreceiver); }}


The activity. Whenever I click on a button to call AddTask, I go back to the simulation to create a task and then hand it to intentservice to handle it.

Note that when each task of the service is completed, a broadcast is sent, and we register the broadcast separately in the activity's OnCreate and OnDestroy, and the specified UI is updated when the broadcast is received.

Layout file

<linearlayout android:id= "@+id/id_ll_taskcontainer"              xmlns:android= "http://schemas.android.com/apk/res/ Android "              xmlns:tools=" Http://schemas.android.com/tools "              android:layout_width=" Match_parent              " android:layout_height= "Match_parent"              android:orientation= "vertical"             >    <button android:layout_ Width= "Wrap_content" android:layout_height= "wrap_content"            android:onclick= "AddTask" android:text= "Add Task"/ ></LinearLayout>

OK, so we're finished with our needs; by the above example, we can see that we can use Intentservice to handle background tasks easily, shielding many details, and service and activity communication, we choose the way of broadcasting (of course, it can also use LocalBroadcastManager).

After learning to use it, let's look at its internal implementation bang.

Three Intentservice source code parsing

See Intentservice source code directly

/* Copyright (C) The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License") ; * You are not a use this file except in compliance with the License. * Obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * unless required by appli Cable law or agreed into writing, software * Distributed under the License is distributed on a "as is" BASIS, * without Warranties or CONDITIONS of any KIND, either express OR implied. * See the License for the specific language governing permissions and * limitations under the License. */package android.app;import android.content.intent;import Android.os.handler;import android.os.HandlerThread; Import Android.os.ibinder;import Android.os.looper;import Android.os.message;public abstract class Intentservice    Extends Service {private volatile Looper mservicelooper;    private volatile Servicehandler Mservicehandler;    Private String Mname;    Private Boolean mredelivery; PRivate Final class Servicehandler extends Handler {public Servicehandler (Looper Looper) {super (Looper)        ;            } @Override public void Handlemessage (Message msg) {onhandleintent ((Intent) msg.obj);        Stopself (MSG.ARG1);        }} public Intentservice (String name) {super ();    Mname = name;    The public void Setintentredelivery (Boolean enabled) {mredelivery = enabled;        } @Override public void OnCreate () {super.oncreate ();        Handlerthread thread = new Handlerthread ("intentservice[" + Mname + "]");        Thread.Start ();        Mservicelooper = Thread.getlooper ();    Mservicehandler = new Servicehandler (mservicelooper);        } @Override public void OnStart (Intent Intent, int startid) {Message msg = Mservicehandler.obtainmessage ();        MSG.ARG1 = Startid;        Msg.obj = Intent;    Mservicehandler.sendmessage (msg); } @Override public int onstartcomMand (Intent Intent, int flags, int startid) {OnStart (Intent, Startid); Return mredelivery?    Start_redeliver_intent:start_not_sticky;    } @Override public void OnDestroy () {mservicelooper.quit ();    } @Override Public IBinder onbind (Intent Intent) {return null; } protected abstract void Onhandleintent (Intent Intent);}

Can see that it initializes a handlerthread inside the oncreate. About the use and source code of Handlerthread
Analysis: Android Handlerthread fully Parse, see this is expected to be able to guess its logic:

is when you call Onstartcommand. Send a message via Mservicehandler, including our intent in the message. Then go back to onhandleintent (intent) in the handlemessage of the Mservicehandler;

So let's look at the source code in detail. Sure enough, the Onstartcommand callback OnStart. The onstart sends a message through Mservicehandler to the handlemessage of the handler. The last Handlemessage callback Onhandleintent (intent).

Note: Call Stopself (MSG.ARG1) when the callback is complete, and note that this msg.arg1 is an int value, which is the equivalent of a request's unique identity. Each time a request is sent, a unique identity is generated, and then the request is placed in the queue when all is finished (the last request is the equivalent of Getlaststartid = = Startid), or the currently sent identity is the one recently issued (Getlaststartid = = Startid). will destroy our service.

Assume that the incoming 1 is destroyed directly.

Then, when the task is finished destroying the service callback ondestory, we can see that our Looper:mServiceLooper.quit () is released in OnDestroy.

Ok~ assume that your needs can be used Intentservice to do, to use as much as possible, the design is still quite good.

Of course. Suppose you need to consider concurrency and so on. Then you may need to expand the thread pool to create it yourself.

Source code click to download

ok~~

Android Intentservice completely parse when service encounters handler

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.