2011-03-02 34 views
0

我正在开发我的第一个Androïd应用程序,当我想要显示ProgressDialog以指示进程正在运行时,我遇到问题。 在我的应用程序中,用户通过按下按钮来触发耗时的任务。当用户按下按钮时,我的“OnClickListener”的“OnClick”功能被调用。在此功能中,这里是目前我在做什么:主题和ProgressDialog

 - creation and configuration of an instance of the ProgressDialog class, 
     - creation of a thread dedicated to the time consuming task, 
     - attempt to display the ProgressDialog using the "show" method, 
     - start of the thread, 
     - main Activity suspended (call of the "wait" function) 
     - wake up of the main Activity by the thread when it is finished 
     - removal of the ProgressDialog by calling the "dismiss" function. 

,一切工作正常(长期任务的结果是正确的),但仍然出现ProgressDialog讷韦尔。我究竟做错了什么?

在此先感谢您花费时间来帮助我。

回答

2

您不应该在主要Activity/UI线程中调用wait(),因为这实际上会冻结UI,包括ProgressDialog,所以它没有时间淡入并且永远不会显示。

尝试使用正确的多线程:http://developer.android.com/resources/articles/painless-threading.html

final Handler transThreadHandler = new Handler(); 

public void onClick(View v) { 
    // show ProgressDialog... 
    new Thread(){ 
     public void run(){ 
      // your second thread 
      doLargeStuffHere(); 
      transThreadHandler.post(new Runnable(){public void run(){ 
       // back in UI thread 
       // close ProgressDialog... 
      }}); 
     } 
    }.start(); 
} 
0

我会建议使用AsyncTask,因为它的目的就是精确地处理这类问题。有关如何使用它的说明,请参阅here。请注意,Floern的答案中的链接页面也建议使用AsyncTask

你需要做到以下几点:

  • AsyncTask
  • 覆盖它onPreExecute()方法来创建和显示ProgressDialog。 (你可以在你的子类的成员中持有对它的引用)
  • 重写它的doInBackground()方法来执行耗时的操作。
  • 覆盖它的隐藏对话框的方法。
  • 在你的活动中,创建你的子类的一个实例,并在其上调用​​。

如果你让你的子类成为你活动的内部类,你甚至可以使用你所有活动的成员。

+0

使用此方法是否满足原始发布者的要求,即暂停主要活动,直到耗时操作完成? – shyamal 2012-06-26 18:34:06

+0

他为什么要这么做? UI线程负责在后台线程运行时显示(动画)进度指示器。 (调用wait()会挂起UI线程,而不是Activity)。如果我正确理解了这个问题,那么该框不包含他的需求,但是他的解决方案会改为尝试。 – user634618 2012-09-06 13:20:54