在没有 AsyncTask 的情况下运行 UIthread

发布于 2024-12-08 18:46:55 字数 397 浏览 0 评论 0原文

在应用程序初始化期间,我有一个任务在 UI 线程上花费了大约 10 秒,我决定将其放在后台线程中,并在执行此操作时显示启动屏幕。我使用 AsyncTask 完成了这项工作...然而,由于 AsyncTasks 优先级被硬编码得很低,而且我找不到办法增加它,所以任务从需要 10 秒才能完成,变成了几分钟。

所以,我的问题是,如何在没有 AsyncTask 的情况下在非 UI 线程上运行任务?到目前为止,我尝试过的所有操作似乎都在 UI 任务上运行,这会阻止 SplashScreen 在任务完成之前出现。

那么如何创建一个线程,并在非 UI 线程上运行它呢?我认为除了 AsyncTask 之外还必须有一个选项,但到目前为止我还没有找到它......处理程序似乎只是在 UI 上运行,就像标准线程/可运行对象一样。这一定是可能的,但我只是不明白。

I have a task that takes about 10 seconds on the UI thread during initialization of my app, I decided to instead put this in a background thread and show a splash screen while this was going on.. I got this working using AsyncTask... however because of AsyncTasks priority being hard coded so low, and no way to increase it that I can find, the task went from taking 10 seconds to finish, to several minutes.

So, the question I have is, how do I run a task on a NON UI thread without AsyncTask? Everything I have tried to so far seems to run on the UI Task which prevents the SplashScreen from appearing until after the task is done.

So how do I create a thread, run it on a non UI thread? I assume there must be an option other than AsyncTask but so far I have not found it... handlers just seem to run on the UI, as do standard threads/runnables. This has to be possible, but I am just not figuring it out.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

落在眉间の轻吻 2024-12-15 18:46:56

既然你已经让 AsyncTask 工作了,也许你可以从 doInBackground() 内部提高它的优先级:

protected Void doInBackground() {
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
    /* do the work */
}

另外,对于 Handler 来说,不完全是这样。确定问题是什么,但您需要在 UI 线程中创建 Handler,显式启动另一个线程来完成您的工作,然后使用该新线程中的处理程序将消息发布到 UI 线程。 AsyncTask 很好,因为它会为您处理所有这些事情。

Since you already got the AsyncTask working, maybe you could just bump it's priority from inside doInBackground():

protected Void doInBackground() {
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
    /* do the work */
}

Also, for the Handler, not exactly sure what the problem was, but you need to create the Handler in the UI thread, explicitly start a different thread to do your work, then use the handler from that new thread to post messages to the UI thread. AsyncTask is nice because it takes care of all this for you.

纵山崖 2024-12-15 18:46:56

只需创建一个Thread,设置您想要的任何优先级并start()它。或者使用 RunnableExecutor。这些不会在 UI 线程上运行。如果您需要在后台工作完成时通知 UI,请在启动线程之前创建一个 Handler 并将其传递给您的 Thread/Runnable。

Simply create a Thread, set any priority you want and start() it. Or use a Runnable and an Executor. Those will not run on the UI thread. If you need to notify the UI when your background work is done, create a Handler before starting the thread and pass it to your Thread/Runnable.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文