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; }
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.
@Override public int onStartCommand(@Nullable Intent intent, int flags, int startId) { onStart(intent, startId); return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY; }
@Override public void onDestroy() { mServiceLooper.quit(); }
@Override @Nullable public IBinder onBind(Intent intent) { return null; }
public Looper getLooper() { if (!isAlive()) { return null; } // If the thread has been started, wait until the looper has been created. synchronized (this) { while (isAlive() && mLooper == null) { try { wait(); } catch (InterruptedException e) { } } } return mLooper; }
public boolean quit() { Looper looper = getLooper(); if (looper != null) { looper.quit(); return true; } return false; }
public boolean quitSafely() { Looper looper = getLooper(); if (looper != null) { looper.quitSafely(); return true; } return false; }
public int getThreadId() { return mTid; } }
分析
IntentService#onCreate
1 2
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]"); thread.start();
@Override public int onStartCommand(@Nullable Intent intent, int flags, int startId) { onStart(intent, startId); return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY; }