Home | History | Annotate | Download | only in app
      1 /*
      2  * Copyright (C) 2008 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package android.app;
     18 
     19 import android.content.Intent;
     20 import android.os.Handler;
     21 import android.os.HandlerThread;
     22 import android.os.IBinder;
     23 import android.os.Looper;
     24 import android.os.Message;
     25 
     26 /**
     27  * IntentService is a base class for {@link Service}s that handle asynchronous
     28  * requests (expressed as {@link Intent}s) on demand.  Clients send requests
     29  * through {@link android.content.Context#startService(Intent)} calls; the
     30  * service is started as needed, handles each Intent in turn using a worker
     31  * thread, and stops itself when it runs out of work.
     32  *
     33  * <p>This "work queue processor" pattern is commonly used to offload tasks
     34  * from an application's main thread.  The IntentService class exists to
     35  * simplify this pattern and take care of the mechanics.  To use it, extend
     36  * IntentService and implement {@link #onHandleIntent(Intent)}.  IntentService
     37  * will receive the Intents, launch a worker thread, and stop the service as
     38  * appropriate.
     39  *
     40  * <p>All requests are handled on a single worker thread -- they may take as
     41  * long as necessary (and will not block the application's main loop), but
     42  * only one request will be processed at a time.
     43  *
     44  * <div class="special reference">
     45  * <h3>Developer Guides</h3>
     46  * <p>For a detailed discussion about how to create services, read the
     47  * <a href="{@docRoot}guide/topics/fundamentals/services.html">Services</a> developer guide.</p>
     48  * </div>
     49  *
     50  * @see android.os.AsyncTask
     51  */
     52 public abstract class IntentService extends Service {
     53     private volatile Looper mServiceLooper;
     54     private volatile ServiceHandler mServiceHandler;
     55     private String mName;
     56     private boolean mRedelivery;
     57 
     58     private final class ServiceHandler extends Handler {
     59         public ServiceHandler(Looper looper) {
     60             super(looper);
     61         }
     62 
     63         @Override
     64         public void handleMessage(Message msg) {
     65             onHandleIntent((Intent)msg.obj);
     66             stopSelf(msg.arg1);
     67         }
     68     }
     69 
     70     /**
     71      * Creates an IntentService.  Invoked by your subclass's constructor.
     72      *
     73      * @param name Used to name the worker thread, important only for debugging.
     74      */
     75     public IntentService(String name) {
     76         super();
     77         mName = name;
     78     }
     79 
     80     /**
     81      * Sets intent redelivery preferences.  Usually called from the constructor
     82      * with your preferred semantics.
     83      *
     84      * <p>If enabled is true,
     85      * {@link #onStartCommand(Intent, int, int)} will return
     86      * {@link Service#START_REDELIVER_INTENT}, so if this process dies before
     87      * {@link #onHandleIntent(Intent)} returns, the process will be restarted
     88      * and the intent redelivered.  If multiple Intents have been sent, only
     89      * the most recent one is guaranteed to be redelivered.
     90      *
     91      * <p>If enabled is false (the default),
     92      * {@link #onStartCommand(Intent, int, int)} will return
     93      * {@link Service#START_NOT_STICKY}, and if the process dies, the Intent
     94      * dies along with it.
     95      */
     96     public void setIntentRedelivery(boolean enabled) {
     97         mRedelivery = enabled;
     98     }
     99 
    100     @Override
    101     public void onCreate() {
    102         // TODO: It would be nice to have an option to hold a partial wakelock
    103         // during processing, and to have a static startService(Context, Intent)
    104         // method that would launch the service & hand off a wakelock.
    105 
    106         super.onCreate();
    107         HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
    108         thread.start();
    109 
    110         mServiceLooper = thread.getLooper();
    111         mServiceHandler = new ServiceHandler(mServiceLooper);
    112     }
    113 
    114     @Override
    115     public void onStart(Intent intent, int startId) {
    116         Message msg = mServiceHandler.obtainMessage();
    117         msg.arg1 = startId;
    118         msg.obj = intent;
    119         mServiceHandler.sendMessage(msg);
    120     }
    121 
    122     /**
    123      * You should not override this method for your IntentService. Instead,
    124      * override {@link #onHandleIntent}, which the system calls when the IntentService
    125      * receives a start request.
    126      * @see android.app.Service#onStartCommand
    127      */
    128     @Override
    129     public int onStartCommand(Intent intent, int flags, int startId) {
    130         onStart(intent, startId);
    131         return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
    132     }
    133 
    134     @Override
    135     public void onDestroy() {
    136         mServiceLooper.quit();
    137     }
    138 
    139     /**
    140      * Unless you provide binding for your service, you don't need to implement this
    141      * method, because the default implementation returns null.
    142      * @see android.app.Service#onBind
    143      */
    144     @Override
    145     public IBinder onBind(Intent intent) {
    146         return null;
    147     }
    148 
    149     /**
    150      * This method is invoked on the worker thread with a request to process.
    151      * Only one Intent is processed at a time, but the processing happens on a
    152      * worker thread that runs independently from other application logic.
    153      * So, if this code takes a long time, it will hold up other requests to
    154      * the same IntentService, but it will not hold up anything else.
    155      * When all requests have been handled, the IntentService stops itself,
    156      * so you should not call {@link #stopSelf}.
    157      *
    158      * @param intent The value passed to {@link
    159      *               android.content.Context#startService(Intent)}.
    160      */
    161     protected abstract void onHandleIntent(Intent intent);
    162 }
    163