我之前使用的是 AsyncTask
,只是出于不值得为这个问题深入探讨的原因而转而使用传统的 Thread
。
我该怎么做才能让某些东西在线程启动之前和之后执行,类似于 onPre/PostExecute 的功能?
例如,假设我想在线程开始前显示一个加载圆圈,并在线程结束时将其关闭。我该怎么做?
对于执行后位,我正在使用 thread.join() 并且它似乎可以解决问题。不过,我不确定这是否是解决问题的方法,或者如何进行预执行。
最佳答案
What can I do to make something execute before and after the thread starts, similar to the functionality of onPre/PostExecute?
onPreExecute()
-> 在 Thread
上调用 start()
之前执行的语句
onPostExecute()
-> 在 View
上调用 runOnUiThread()
或 post()
,从您的 Thread
,提供要在主应用程序线程上执行的 Runnable
How would I do that?
理想情况下,您不会。进度对话框很烂。在您的 UI 某处(例如,操作栏、标题栏)放置一个进度指示器,并禁用用户在您的线程运行时不能安全地做的几件事。
也就是说,您可能会在执行线程之前显示 DialogFragment
,然后通过上述机制在线程完成后删除该 fragment 。
For the post-execution bit, I'm using thread.join() and it seems to do the trick.
恶心。这将阻塞您所在的任何线程,如果那是主应用程序线程,那真的很糟糕。
更新
runOnUiThread()
示例:
new Thread() {
public void run() {
// do cool stuff
runOnUiThread(new Runnable() {
public void run() {
// do other cool stuff quickly on the main application thread
}
);
}
}).start();
关于java - 有没有类似于传统线程的onPreExecute和onPostExecute的东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12904622/