正如docmentation所说,我试图了解intentService如何在单一后台线程中完成所有工作。所以我深入研究源代码,并提出问题
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之后的下一个调用是 stopSelf(msg.arg1); 。据我所知,在此之后,服务被破坏,但HandlerThread继续处理消息。在销毁之后,假设我再发送一个服务意图。由于intentservice被销毁,这会调用onCreate并创建另一个HandlerThread !! ,之后没有几个Worker线程,不像Single那样文档说。 有人可以解释我,我错了吗?
答案 0 :(得分:1)
据我了解,此后,服务被销毁
没有。如果您致电stopSelf()
,服务将停止。但是,如果没有其他未提交的stopSelf(int)
已发送到服务,Intents
将仅停止服务。