HandlerThread異步
爲何要使用HandlerThread?ide
咱們常常使用的Handler來處理消息,其中使用Looper來對消息隊列進行輪詢,而且默認是發生在主線程中,這可能會引發UI線程的卡頓,因此咱們用HandlerThread來替代。。。oop
HanderThread實際上就是一個線程this
@Override public void run() { mTid = Process.myTid(); Looper.prepare(); synchronized (this) { mLooper = Looper.myLooper(); notifyAll(); } Process.setThreadPriority(mPriority); onLooperPrepared(); Looper.loop(); mTid = -1; }
獲取Looper的時候,若是還沒建立好,會進行等待。。。spa
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; }
使用方法:線程
HandlerThread thread=new HandlerThread("hello"); thread.start();//必須得先start Handler handler=new Handler(thread.getLooper(), new Handler.Callback() { @Override public boolean handleMessage(Message msg) { //發生hello線程中。。。。 return false; } }); handler.sendEmptyMessage(0);
爲何須要使用IntentService?code
Service裏面咱們確定不能直接進行耗時操做,通常都須要去開啓子線程去作一些事情,本身去管理Service的生命週期以及子線程並不是是個優雅的作法;好在Android給咱們提供了一個類,叫作IntentService
blog
意思說IntentService是一個基於Service的一個類,用來處理異步的請求。你能夠經過startService(Intent)來提交請求,該Service會在須要的時候建立,當完成全部的任務之後本身關閉,且請求是在工做線程處理的。生命週期
這麼說,咱們使用了IntentService最起碼有兩個好處,一方面不須要本身去new Thread了;另外一方面不須要考慮在何時關閉該Service了。隊列
內部實現仍是使用的HandlerThread
@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); }
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); } } @Override public void onStart(Intent intent, int startId) { Message msg = mServiceHandler.obtainMessage(); msg.arg1 = startId; msg.obj = intent; mServiceHandler.sendMessage(msg); }