问题
I am trying to display a progress dialog during downloading of data.
Right now, this is what I have:
final ProgressDialog pd = ProgressDialog.show(this, "Updating", "Loading...");
Thread td = new Thread(new Runnable(){
public void run(){
//time consuming download
pd.dismiss();
}
});
td.start(); // start the thread and use join to wait for it to return
td.join(); //wrapped in try catch not shown here
I don't need progress updates from the download, and the app shouldn't do anything else until the data is downloaded, that's why I use join - so it'll wait for the download to finish.
The result I'm getting is
- Push button
- UI freezes
- progress dialog flashes on and off, download is done
what I need is
- Push button
- progress dialog shows
- progress dialog turns off, download is done.
Any idea why it's not showing right away, and instead flashing on and off when it is done?
回答1:
In never used join
but when I read the documentation it says that the other thread (the UI thread here) will be blocked until the working thread is finished. So this explains the behavior you describe quite good.
Use a AsyncTask instead. Do the download in doInBackground
and process the result in onPostExecute
and it'll work...
回答2:
The typical solution to handle a download in the background is to use AsyncTask() instead of a Thread.
http://developer.android.com/reference/android/os/AsyncTask.html
Then your progress dialog will show up correctly if you follow the suggestions in the documentation.
来源:https://stackoverflow.com/questions/7939563/android-ui-freezes-instead-of-displaying-progressdialog