Android UI Freezes instead of displaying ProgressDialog

落爺英雄遲暮 提交于 2020-01-07 08:05:48

问题


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

  1. Push button
  2. UI freezes
  3. progress dialog flashes on and off, download is done

what I need is

  1. Push button
  2. progress dialog shows
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!