2016-04-22 238 views
2
的內部運作

我試圖理解邏輯的特定位IntentService,具體而言,在ServiceHandler澄清IntentService

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); 
    } 
} 

從我可以告訴,stopSelf()被稱爲多次 - 一次每撥打一次startService。如果有多個項目要處理,stopSelf是否不會中斷待處理項目的流程?顯然這不是發生了什麼,因爲IntentService實際上工作,但爲什麼?看起來像stopSelf應該在處理完所有Intent之後調用。

另一個問題--創建的HandlerThread何時會實際停止?顯然它不會被stopSelf阻止?

+0

你並不需要調用'stopSelf'一個'IntentService'。更多信息在這裏:http://stackoverflow.com/questions/10250745/proper-way-to-stop-intentservice –

+0

事實上,因爲'IntentService'確實實際的調用。我的問題是關於班級的內部運作。 – Melllvar

回答

2

如果stopSelf(int startId)最近一次啓動的時間是startId,則該方法將僅停止Service。如果IntentService在它仍然處理Intent時再次啓動,則將傳遞一個不同的startId給它,因此調用stopSelf()與之前的startId不會阻止它。

HandlerThread開始onCreate()Service實例確實會死,作爲其Looper終止在IntentServiceonDestroy()方法。

+1

完美答案,謝謝! – Melllvar

1

stopSelf(int)電話stopSelfResult(int)它說:

停止該服務,如果它開始的最近時間爲startId。這與針對此特定服務調用stopService(Intent)的功能相同,但如果客戶端有您尚未在onStart(Intent, int)中看到的啓動請求,則可以安全地避免停止。

由於IntentService只做爲了工作,也不會真正停止,直到最後startId發送到stopSelf