gpt4 book ai didi

android - 如何终止 HandlerThreads?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:56:45 25 4
gpt4 key购买 nike

按照 Google 使用服务的示例,我创建了几个这样的线程。我不能使用 IntentService,因为我正在做一些涉及等待回调的事情。

但是,我不知道如何终止以这种方式启动的线程。据我了解,线程会在 run() 方法返回时自动终止。但是,这种线程没有运行方法。我的线程正在泄漏——它们在 stopSelf() 之后仍然存在。

@Override
public void onCreate() {

HandlerThread thread = new HandlerThread("ServiceStartArguments",
android.os.Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
HandlerThread thread2 = new HandlerThread("CallbackHandling",
android.os.Process.THREAD_PRIORITY_BACKGROUND);
thread2.start();

mServiceLooper = thread.getLooper();
mCallbackLooper = thread2.getLooper();
mServiceHandler = new MyHandler(mServiceLooper);
mCallbackHandler = new Handler(mCallbackLooper);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();

// For each start request, send a message to start a job and deliver the
// start ID so we know which request we're stopping when we finish the job
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);
mMainThreadHandler=new Handler();
// If we get killed, after returning from here, restart
return START_STICKY;
}

private final class MyHandler extends Handler {
public MyHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
cycle();


// Stop the service using the startId, so that we don't stop
// the service in the middle of handling another job
stopSelf(msg.arg1);
}
}

protected void cycle() {
...
mCallbackHandler.post(new Runnable(){
public void run(){
goAskForSomeCallbacks();
}
});

try {
Thread.sleep(GIVE_UP_TIME);
} catch (InterruptedException e){
//The callback will interrupt this thread to stop it from waiting
Log.d(TAG,"Got early callback, stop waiting.");
}
Thread.interrupted(); //clear the interrupt
doStuff();

}

最佳答案

尝试在相应的 Looper 上调用 quit 方法。

关于android - 如何终止 HandlerThreads?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5391085/

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