gpt4 book ai didi

android - IntentService 和 HandlerThread 计数

转载 作者:行者123 更新时间:2023-11-30 02:21:52 26 4
gpt4 key购买 nike

我正在尝试了解 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 队列。
但是假设服务接收到多个 Intent ,并将所有 Intent 添加到队列中。但是在处理完first 消息后,handleMessage 中onHandleIntent 之后的下一个调用是stopSelf(msg.arg1);。据我了解,在此之后,服务被破坏,但 HandlerThread 继续处理消息。在销毁之后,假设我再发送一个服务 Intent 。由于 intentservice 被销毁,调用 onCreate 并创建另一个 HandlerThread!!,之后没有多个工作线程,不像文档中所说的单个线程。有人可以解释一下我哪里错了吗?

最佳答案

As i understand, after this, service is destroyed

没有。如果调用 stopSelf(),服务将停止。但是,stopSelf(int) 只会在没有其他未完成的 Intents 已交付给服务时停止服务。

关于android - IntentService 和 HandlerThread 计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28384607/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com