在没有 AsyncTask 的情况下运行 UIthread
在应用程序初始化期间,我有一个任务在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
既然你已经让
AsyncTask
工作了,也许你可以从doInBackground()
内部提高它的优先级:另外,对于
Handler
来说,不完全是这样。确定问题是什么,但您需要在 UI 线程中创建 Handler,显式启动另一个线程来完成您的工作,然后使用该新线程中的处理程序将消息发布到 UI 线程。AsyncTask
很好,因为它会为您处理所有这些事情。Since you already got the
AsyncTask
working, maybe you could just bump it's priority from insidedoInBackground()
:Also, for the
Handler
, not exactly sure what the problem was, but you need to create theHandler
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.只需创建一个
Thread
,设置您想要的任何优先级并start()
它。或者使用Runnable
和Executor
。这些不会在 UI 线程上运行。如果您需要在后台工作完成时通知 UI,请在启动线程之前创建一个 Handler 并将其传递给您的 Thread/Runnable。Simply create a
Thread
, set any priority you want andstart()
it. Or use aRunnable
and anExecutor
. Those will not run on the UI thread. If you need to notify the UI when your background work is done, create aHandler
before starting the thread and pass it to yourThread/Runnable
.