2016-04-22 115 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