Intentservice
1 @Override 2 public void onCreate() { 3 // TODO: It would be nice to have an option to hold a partial wakelock 4 // during processing, and to have a static startService(Context, Intent) 5 // method that would launch the service & hand off a wakelock. 6 7 super.onCreate(); 8 HandlerThread thread = new HandlerThread("IntentService[" + mName + "]"); 9 thread.start(); 10 11 mServiceLooper = thread.getLooper(); 12 mServiceHandler = new ServiceHandler(mServiceLooper); 13 }
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); } }
1 protected abstract void onHandleIntent(Intent intent);
1 public class HandlerThread extends Thread { 2 private int mPriority; 3 private int mTid = -1; 4 private Looper mLooper; 5 6 public HandlerThread(String name) { 7 super(name); 8 mPriority = Process.THREAD_PRIORITY_DEFAULT; 9 } 10 11 /** 12 * Constructs a HandlerThread. 13 * @param name 14 * @param priority The priority to run the thread at. The value supplied must be from 15 * {@link android.os.Process} and not from java.lang.Thread. 16 */ 17 public HandlerThread(String name, int priority) { 18 super(name); 19 mPriority = priority; 20 } 21 22 /** 23 * Call back method that can be explicitly over ridden if needed to execute some 24 * setup before Looper loops. 25 */ 26 protected void onLooperPrepared() { 27 } 28 29 public void run() { 30 mTid = Process.myTid(); 31 Looper.prepare(); 32 synchronized (this) { 33 mLooper = Looper.myLooper(); 34 notifyAll(); 35 } 36 Process.setThreadPriority(mPriority); 37 onLooperPrepared(); 38 Looper.loop(); 39 mTid = -1; 40 } 41 42 /** 43 * This method returns the Looper associated with this thread. If this thread not been started 44 * or for any reason is isAlive() returns false, this method will return null. If this thread 45 * has been started, this method will block until the looper has been initialized. 46 * @return The looper. 47 */ 48 public Looper getLooper() { 49 if (!isAlive()) { 50 return null; 51 } 52 53 // If the thread has been started, wait until the looper has been created. 54 synchronized (this) { 55 while (isAlive() && mLooper == null) { 56 try { 57 wait(); 58 } catch (InterruptedException e) { 59 } 60 } 61 } 62 return mLooper; 63 } 64 65 /** 66 * Ask the currently running looper to quit. If the thread has not 67 * been started or has finished (that is if {@link #getLooper} returns 68 * null), then false is returned. Otherwise the looper is asked to 69 * quit and true is returned. 70 */ 71 public boolean quit() { 72 Looper looper = getLooper(); 73 if (looper != null) { 74 looper.quit(); 75 return true; 76 } 77 return false; 78 } 79 80 /** 81 * Returns the identifier of this thread. See Process.myTid(). 82 */ 83 public int getThreadId() { 84 return mTid; 85 } 86 }