2015-02-07 22 views
1

我想了解intentService如何在單個後臺線程中完成所有工作,如文檔說明所述。所以我深入源代碼,並有一個問題IntentService和HandlerThread計數

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); 
     } 
    } 
    /** 
    * Creates an IntentService. Invoked by your subclass's constructor. 
    * 
    * @param name Used to name the worker thread, important only for debugging. 
    */ 
    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. 
     super.onCreate(); 
     HandlerThread thread = new HandlerThread("IntentService[" + mName + "]"); 
     thread.start(); 
     mServiceLooper = thread.getLooper(); 
     mServiceHandler = new ServiceHandler(mServiceLooper); 
    } 
    @Override 
    public void onStart(Intent intent, int startId) { 
     Message msg = mServiceHandler.obtainMessage(); 
     msg.arg1 = startId; 
     msg.obj = intent; 
     mServiceHandler.sendMessage(msg); 
    } 
    /** 
    * You should not override this method for your IntentService. Instead, 
    * override {@link #onHandleIntent}, which the system calls when the IntentService 
    * receives a start request. 
    * @see android.app.Service#onStartCommand 
    */ 
    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     onStart(intent, startId); 
     return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY; 
    } 
    @Override 
    public void onDestroy() { 
     mServiceLooper.quit(); 
} 

所以在onCreate服務一個HandlerThread創建。在此之後,所有onStartCommand調用都會將消息添加到HanlderThread隊列中。
但假設服務收到幾個意圖,並將所有意向添加到隊列中。但在處理完之後的第一個消息後,在handleMessage中onHandleIntent之後的下一個call是stopSelf(msg.arg1);。據我所知,在此之後,服務被銷燬,但HandlerThread保持處理消息。在銷燬之後,假設我再發送一個意向服務。由於intentservice被破壞,這調用onCreate並創建另一個HandlerThread !!,之後沒有多個工作者線程,與單據不同,如文檔所述。 有人可以解釋我,我錯了嗎?

回答

1

據我瞭解,在此之後,服務被破壞

號如果調用stopSelf(),該服務被停止。但是,stopSelf(int)只會在傳送到服務的其他未完成Intents停止服務。

+0

當intentservice被銷燬嗎? – orium 2015-02-07 16:59:07

+0

@orium:'onStartCommand()'傳遞一個'int',通常名爲'startId'。這是您傳遞給'stopSelf()'的值,它們按照到達'onStartCommand()'的順序。一旦將最後一個'startId'傳遞給'stopSelf()',服務將被銷燬。 – CommonsWare 2015-02-07 17:01:32