IntentService.java revision 3dec7d563a2f3e1eb967ce2054a00b6620e3558c
1package android.app;
2
3import android.content.Intent;
4import android.os.Handler;
5import android.os.HandlerThread;
6import android.os.IBinder;
7import android.os.Looper;
8import android.os.Message;
9
10/**
11 * An abstract {@link Service} that serializes the handling of the Intents passed upon service
12 * start and handles them on a handler thread.
13 *
14 * <p>To use this class extend it and implement {@link #onHandleIntent}. The {@link Service} will
15 * automatically be stopped when the last enqueued {@link Intent} is handled.
16 */
17public abstract class IntentService extends Service {
18    private volatile Looper mServiceLooper;
19    private volatile ServiceHandler mServiceHandler;
20    private String mName;
21
22    private final class ServiceHandler extends Handler {
23        public ServiceHandler(Looper looper) {
24            super(looper);
25        }
26
27        @Override
28        public void handleMessage(Message msg) {
29            onHandleIntent((Intent)msg.obj);
30            stopSelf(msg.arg1);
31        }
32    }
33
34    public IntentService(String name) {
35        super();
36        mName = name;
37    }
38
39    @Override
40    public void onCreate() {
41        super.onCreate();
42        HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
43        thread.start();
44
45        mServiceLooper = thread.getLooper();
46        mServiceHandler = new ServiceHandler(mServiceLooper);
47    }
48
49    @Override
50    public void onStart(Intent intent, int startId) {
51        super.onStart(intent, startId);
52        Message msg = mServiceHandler.obtainMessage();
53        msg.arg1 = startId;
54        msg.obj = intent;
55        mServiceHandler.sendMessage(msg);
56    }
57
58    @Override
59    public void onDestroy() {
60        mServiceLooper.quit();
61    }
62
63    @Override
64    public IBinder onBind(Intent intent) {
65        return null;
66    }
67
68    /**
69     * Invoked on the Handler thread with the {@link Intent} that is passed to {@link #onStart}.
70     * Note that this will be invoked from a different thread than the one that handles the
71     * {@link #onStart} call.
72     */
73    protected abstract void onHandleIntent(Intent intent);
74}
75