简体   繁体   English

显示ProgressDialog时挂起Android应用程序的主线程

[英]Suspend Android app's main thread while showing the ProgressDialog

When my Android app is starting up needs to load a lot of data from the database during onCreate in the firstly loaded activity. 在我的Android应用启动时,需要在首次加载的活动中的onCreate期间从数据库中加载大量数据。 I would like to show a ProgressDialog for that. 我想为此显示一个ProgressDialog。 ProgressDialog however can't be shown in the main thread, so one must use AsyncTask or new Thread. 但是ProgressDialog无法显示在主线程中,因此必须使用AsyncTask或新线程。 But that also means, that the activity continues to be initialized as the main thread goes on. 但这也意味着,随着主线程的继续,活动将继续初始化。

Basically, I need to show the ProgressDialog or a kind of its equivalent while processing in the main thread (not in AsyncTask). 基本上,我需要在主线程(而不是AsyncTask)中进行处理时显示ProgressDialog或它的等效形式。

Is there a way to do it? 有办法吗?

The Main/UI Thread is responsible for drawing the UI, and hence, the ProgressDialog itself . Main/UI线程负责绘制UI,因此负责ProgressDialog本身。 So you can not block it and hope that he is going to draw the UI. 因此,您不能阻止它,并希望他将绘制UI。 You should move the initialization stuff inside AsyncTask 's doInBackgroud , and move on with the other suff after onPostExecuted is called 您应该将初始化工作移到AsyncTaskdoInBackgroud内部,并在调用onPostExecuted 之后 onPostExecuted进行其他操作

You will never be able to show progress because your view of activity have not created, because you read from database in onCreate methode after reading the database onCreate method finshes and now your view inflate and so on . 您将永远无法显示进度,因为您的活动视图尚未创建,因为您在读取数据库onCreate方法后又从onCreate方法中的数据库中读取数据,现在视图膨胀等等。 . .

您应该使用线程(ASyncTask)加载数据,并使用“ onPreExecute()”显示ProgressDialog,并使用“ onProgressUpdate()”更新它,并使用“ onPostExecute()”结束对话框,所有这些都已在UI线程上运行。

ProgressDialog however can't be shown in the main thread, so one must use AsyncTask or new Thread. 但是ProgressDialog无法显示在主线程中,因此必须使用AsyncTask或新线程。

How do you come to this conclusion? 您如何得出这个结论? ALL UI stuff is shown in the UI Thread, thus also the ProgressDialog. 所有UI内容都显示在UI线程中,因此也显示ProgressDialog。 It needs to be created and invoked inside the UI Thread to work or else your App crashes. 需要在UI线程中创建并调用它,否则它会崩溃。

First you need to check on onCreate() if your stuff is already loaded and if not, show a ProgressDialog, load stuff in the background and then do a post in the UI Thread to dismiss the ProgressDialog and show the results. 首先,您需要检查onCreate()是否已加载您的内容,如果尚未加载,请显示一个ProgressDialog,在后台加载该内容,然后在UI线程中进行发布以关闭ProgressDialog并显示结果。

That's how it usually works. 这就是通常的工作方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM