gpt4 book ai didi

android - 与线程混淆 - 处理程序阻塞 UI 线程

转载 作者:行者123 更新时间:2023-11-29 14:21:04 26 4
gpt4 key购买 nike

我有一个耗时的任务(遍历文件并将其内容发送到服务器),我想在后台线程中以特定的间隔执行(这就是我想使用 Handler 的原因)。

从 UI 线程我有这样的调用:

LogsManager lm;
lm = new LogsManager(this);
lm.processLogFiles();

LogsManager 类中,我有以下代码:

public void processLogFiles(){
Handler mHandler = new Handler();
mHandler.postDelayed(logsRunable, 1000);
}

private Runnable logsRunable = new Runnable() {
@Override
public void run() {
File f = new File(Environment.getExternalStorageDirectory()+Constants.LOG_DIR);
File[] logFiles = f.listFiles();
for (int i = 0; i < logFiles.length; i++) {
readLogs(logFiles[i]); // executes some other methods inside
}
}
};

如您所见,它只是调用 RunnableHandler 方法。而且,不幸的是,它也阻塞了我的 UI 线程。 Handler 不应该为 Runnable 启动一个新线程吗?我也在我的应用程序的其他部分使用处理程序,它们工作得很好。我做错了什么吗?

最佳答案

the docs 中所述, 处理程序:

When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it

因此,如果您在 UI 线程中创建 mHandler,那么它将在 UI 线程中运行任务 - 因此会出现问题。

关于android - 与线程混淆 - 处理程序阻塞 UI 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6979077/

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