An example of getting started with IntentService

Source: Internet
Author: User

 

I wrote an article about AsyncTask at http://blog.csdn.net/lincyang/article/details/6617802.
The functions provided by IntentService today are similar. They all process asynchronous work.
The workflow is also very simple. The client calls it through the startService (Intent) method. After the service is started, the worker thread is enabled to process intent tasks in sequence. Note that an intentService can process multiple tasks in one sequence. AsyncTask generally starts a new asycnTask for each task, one asyncTask can only be used once. If you want to use it again, you have to create another task. Otherwise, an exception is reported. In terms of appearance, this is the difference between the two. After the task is completed, IntentService automatically stops.
IntentService is inherited from the Service. From the source code, IntentService is a powerful combination of Service, HandlerThread, and Handler. The source code is also simpler than AsyncTask. If you are interested, you can check it out.

Next we will talk about its usage. Like AsyncTask, to use IntentService, you must write a class and inherit it.
Because IntentService itself is inherited from the Service, you must first register it in AndroidManifest. xml when using it. Otherwise, the following error occurs: Unable to start service Intent not found.
IntentService has seven methods, the most important of which is onHandleIntent (). Here, the worker thread is called to process the work. Only one intent is processed at a time, as described above. If there are multiple, it processes the data sequentially until the last processing is completed, and then closes itself. We don't have to worry about it at all. How nice it is.
Next we will introduce another interesting method, setIntentRedelivery (). Literally, intent resend is set. If it is set to true, onStartCommand (Intent, int, int) will return START_REDELIVER_INTENT. If onHandleIntent (Intent) returns the previous process to death, the process will be restarted and intent will be re-delivered, if a large number of intents are delivered, only the latest intent will be redelivered. This mechanism is also very good. You can try it.
Below is a small example. Like asyncTask, this example simulates time-consuming tasks. The broadcast mechanism is added to transmit messages.
AndroidManifest. xml

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"      package="com.linc.TestIntentService"      android:versionCode="1"      android:versionName="1.0">    <application android:icon="@drawable/icon" android:label="@string/app_name">        <activity android:name=".TestIntentService"                  android:label="@string/app_name">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <service android:name=".LincIntentService"></service>    </application></manifest> 

Xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    ><TextView  android:id="@+id/text"    android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:textSize="30sp"    android:textColor="#FF0000"    android:text="@string/hello"    />     <Button android:id="@+id/btnStart" android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:text="Start" />   <Button android:id="@+id/btnSendOther" android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:text="SendOtherBroadcast" /></LinearLayout>

Activity

Package com. linc. testIntentService; import android. app. activity; import android. app. intentService; import android. content. broadcastReceiver; import android. content. context; import android. content. intent; import android. content. intentFilter; import android. OS. bundle; import android. OS. systemClock; import android. text. format. dateFormat; import android. util. log; import android. view. view; import android. widget. button; import android. widget. textView; import android. widget. toast; public class TestIntentService extends Activity {private final static String Tag = "TestIntentService"; private TextView text; private Button btnStart; private Button btnSendOther; private MessageReceiver extends er; /** Action */private static final String ACTION_RECV_MSG = "com. linc. intent. action. RECEIVE_MESSAGE "; private static final String ACTION_OTHER_MSG =" com. linc. intent. action. OTHER_MESSAGE ";/** Message */private static final String MESSAGE_IN =" message_input "; private static final String MESSAGE_OUT =" message_output ";/** Called when the activity is first created. * // @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); text = (TextView) findViewById (R. id. text); text. setText ("prepared"); btnStart = (Button) findViewById (R. id. btnStart); btnStart. setOnClickListener (new View. onClickListener () {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stub Intent msgIntent = new Intent (TestIntentService. this, LincIntentService. class); msgIntent. putExtra (MESSAGE_IN, text. getText (). toString (); startService (msgIntent) ;}}); btnSendOther = (Button) findViewById (R. id. btnSendOther); btnSendOther. setOnClickListener (new View. onClickListener () {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stub}); // dynamically register aggreger IntentFilter filter = new IntentFilter (ACTION_RECV_MSG ); filter. addCategory (Intent. CATEGORY_DEFAULT); receiver = new MessageReceiver (); registerReceiver (receiver, filter); IntentFilter filter2 = new IntentFilter (ACTION_OTHER_MSG); filter2.addCategory (Intent. CATEGORY_DEFAULT); receiver ER = new receiver (); registerReceiver (receiver er, filter2);} // broadcast to receive public class MessageReceiver extends BroadcastReceiver {@ Override public void onReceive (Context context Context, intent intent) {String message = intent. getStringExtra (MESSAGE_OUT); text. setText (message); Toast. makeText (context, "message", Toast. LENGTH_SHORT ). show ();}}}

IntentService

package com.linc.TestIntentService;import android.app.IntentService;import android.content.Intent;import android.os.IBinder;import android.os.SystemClock;import android.text.format.DateFormat;import android.util.Log;//IntentServicepublic class LincIntentService extends IntentService {/* * Action */private static final String ACTION_RECV_MSG = "com.linc.intent.action.RECEIVE_MESSAGE";private static final String ACTION_OTHER_MSG = "com.linc.intent.action.OTHER_MESSAGE";/* * Message */private static final String MESSAGE_IN="message_input";private static final String MESSAGE_OUT="message_output";private final static String Tag="---LincIntentService";    public LincIntentService() {        super("LincIntentService");        Log.d(Tag, "Constructor");     }    @Override    public IBinder onBind(Intent intent) {         Log.d(Tag, "onBind()");         return super.onBind(intent);     }       @Override    public void onCreate() {         Log.d(Tag, "onCreate()");         super.onCreate();     }       @Override    public void onDestroy() {         Log.d(Tag, "onDestroy()");         super.onDestroy();     }       @Override    public void onStart(Intent intent, int startId) {         Log.d(Tag, "onStart()");         super.onStart(intent, startId);     }       @Override    public int onStartCommand(Intent intent, int flags, int startId) {         Log.d(Tag, "onStartCommand()");         return super.onStartCommand(intent, flags, startId);     }       @Override    public void setIntentRedelivery(boolean enabled) {         Log.d(Tag, "setIntentRedelivery()");         super.setIntentRedelivery(enabled);     }     @Override    protected void onHandleIntent(Intent intent) {    Log.d(Tag, "LincIntentService is onHandleIntent!");        String msgRecv = intent.getStringExtra(MESSAGE_IN);    for (int i = 0; i < 5; i++) {    String resultTxt = msgRecv + " "    + DateFormat.format("MM/dd/yy hh:mm:ss", System.currentTimeMillis());    Intent broadcastIntent = new Intent();    broadcastIntent.setAction(ACTION_RECV_MSG);    broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);    broadcastIntent.putExtra(MESSAGE_OUT, resultTxt);    sendBroadcast(broadcastIntent);SystemClock.sleep(1000);}    }//    <service android:name=".LincIntentService"></service>}

From these two articles, we can see that andorid provides these two tools to process time-consuming tasks, which brings great convenience to our developers. Following the source code can also increase our level to a higher level. It seems that the documents and examples provided by android are a treasure, and we should make good use of them!
Add source code

/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * *      http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "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;/** * 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 it runs out of work. * * <p>This "work queue processor" pattern is commonly used to offload tasks * from an application's main thread.  The IntentService class exists to * simplify this pattern and take care of the mechanics.  To use it, extend * IntentService and implement {@link #onHandleIntent(Intent)}.  IntentService * will receive the Intents, launch a worker thread, and stop the service as * appropriate. * * <p>All requests are handled on a single worker thread -- they may take as * long as necessary (and will not block the application's main loop), but * only one request will be processed at a time. * * @see android.os.AsyncTask */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);        }    }    /**     * Creates an IntentService.  Invoked by your subclass's constructor.     *     * @param name Used to name the worker thread, important only for debugging.     */    public IntentService(String name) {        super();        mName = name;    }    /**     * Sets intent redelivery preferences.  Usually called from the constructor     * with your preferred semantics.     *     * <p>If enabled is true,     * {@link #onStartCommand(Intent, int, int)} will return     * {@link Service#START_REDELIVER_INTENT}, so if this process dies before     * {@link #onHandleIntent(Intent)} returns, the process will be restarted     * and the intent redelivered.  If multiple Intents have been sent, only     * the most recent one is guaranteed to be redelivered.     *     * <p>If enabled is false (the default),     * {@link #onStartCommand(Intent, int, int)} will return     * {@link Service#START_NOT_STICKY}, and if the process dies, the Intent     * dies along with it.     */    public void setIntentRedelivery(boolean enabled) {        mRedelivery = enabled;    }    @Override    public void onCreate() {        // TODO: It would be nice to have an option to hold a partial wakelock        // during processing, and to have a static startService(Context, Intent)        // method that would launch the service & hand off a wakelock.        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;    }    /**     * This method is invoked on the worker thread with a request to process.     * Only one Intent is processed at a time, but the processing happens on a     * worker thread that runs independently from other application logic.     * So, if this code takes a long time, it will hold up other requests to     * the same IntentService, but it will not hold up anything else.     *     * @param intent The value passed to {@link     *               android.content.Context#startService(Intent)}.     */    protected abstract void onHandleIntent(Intent intent);}

 

 

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.