简体   繁体   中英

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. I would like to show a ProgressDialog for that. ProgressDialog however can't be shown in the main thread, so one must use AsyncTask or new Thread. 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).

Is there a way to do it?

The Main/UI Thread is responsible for drawing the UI, and hence, the ProgressDialog itself . So you can not block it and hope that he is going to draw the UI. You should move the initialization stuff inside AsyncTask 's doInBackgroud , and move on with the other suff after onPostExecuted is called

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 . . .

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

ProgressDialog however can't be shown in the main thread, so one must use AsyncTask or new Thread.

How do you come to this conclusion? ALL UI stuff is shown in the UI Thread, thus also the ProgressDialog. It needs to be created and invoked inside the UI Thread to work or else your App crashes.

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.

That's how it usually works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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