【问题标题】:Threads and ProgressDialog线程和进度对话框
【发布时间】:2011-03-02 17:04:34
【问题描述】:

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

       - 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 永远不会出现。我做错了什么?

提前感谢您花时间帮助我。

【问题讨论】:

    标签: android multithreading progressdialog


    【解决方案1】:

    您不应该将wait() 调用到 Main Activity/UI 线程,因为这实际上会冻结 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();
    }
    

    【讨论】:

      【解决方案2】:

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

      您需要执行以下操作:

      • 子类AsyncTask
      • 覆盖它的onPreExecute() 方法以创建并显示ProgressDialog。 (您可以在子类的成员中引用它)
      • 覆盖它的doInBackground() 方法以执行您耗时的操作。
      • 覆盖它的 onPostExecute() 方法以隐藏您的对话框。
      • 在您的活动中,创建您的子类的实例并在其上调用execute()。

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

      【讨论】:

      • 使用这种方法能满足原发帖者暂停主Activity直到耗时动作完成的要求吗?
      • 他为什么要这么做? UI 线程负责在后台线程运行时显示(动画)进度指示器。 (调用 wait() 将暂停 UI 线程,而不是 Activity。)如果我正确理解了这个问题,该框不包含他的要求,而是他的解决方案尝试。
      猜你喜欢
      • 2010-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多