Android ProgressDialog 存在线程问题

发布于 2024-10-19 06:57:25 字数 540 浏览 9 评论 0原文

我在进程运行时使用 ProgressDialog 时遇到问题。我已经尝试了所有可能的错误方法,并且查看了许多网站,它们提供了我正在尝试做的事情的示例,但是,我仍然遇到线程在 ProgressDialog 出现之前运行的问题。这是我对此的最新尝试:

new Thread(new Runnable() {
     public void run() {
        dialog = new ProgressDialog(EPD.this);
        dialog.setMessage("Loading. Please Wait...");
        dialog.show();         
                    }
 }).run();
 getMostWanted();                       

除了尝试这种方式之外,我还尝试在 getMostWanted() 中创建一个新线程,但我仍然得到相同的结果。当 getMostWanted() 时,它会暂停大约 4 或 5 秒,并且没有对话框。

预先感谢您的帮助。

I am running into a problem using the ProgressDialog while a process is running. I have tried every incorrect way possible and have looked at numerous websites which offered examples of what I am trying to do however, I am still running into the problem that the thread is running before the ProgressDialog ever comes up. Here is my latest attempt at this:

new Thread(new Runnable() {
     public void run() {
        dialog = new ProgressDialog(EPD.this);
        dialog.setMessage("Loading. Please Wait...");
        dialog.show();         
                    }
 }).run();
 getMostWanted();                       

In addition to trying this way, I have also attempted to a new Thread in getMostWanted() however I am still having the same result. It pauses for ~4 or 5 seconds while getMostWanted() and no dialog box.

Thanks in advance for the help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

北城孤痞 2024-10-26 06:57:25

如果您位于主线程上,则应该使用它来显示 ProgressDialog 并为 getMostWanted() 分离另一个线程。假设您希望 getMostWanted() 结束来关闭对话框,您应该查看 AsyncTask

private class GetMostWanted extends AsyncTask<Void, Void, Void> {
     private final ProgressDialog dialog;

     public GetMostWanted() {
          dialog = new ProgressDialog(EPD.this);
          dialog.setMessage("Loading. Please Wait...");
     }

     protected void onPreExecute() {
         dialog.show();
     }

     protected void doInBackground(Void... unused) {
         getMostWanted();
     }

     protected void onPostExecute(Void unused) {
         dialog.dismiss();
     }
 }

这样您的处理是在 doInBackground() 的后台线程上执行的,完成后您可以在主线程上关闭对话框onPostExecute()

现在您可以使用:

new GetMostWanted(dialog).execute();

If you're on the main thread, you should use that to display the ProgressDialog and spin off another thread for getMostWanted(). Assuming you want the ending of getMostWanted() to dismiss the dialog, you should look at AsyncTask:

private class GetMostWanted extends AsyncTask<Void, Void, Void> {
     private final ProgressDialog dialog;

     public GetMostWanted() {
          dialog = new ProgressDialog(EPD.this);
          dialog.setMessage("Loading. Please Wait...");
     }

     protected void onPreExecute() {
         dialog.show();
     }

     protected void doInBackground(Void... unused) {
         getMostWanted();
     }

     protected void onPostExecute(Void unused) {
         dialog.dismiss();
     }
 }

That way your processing is performed on a background thread in doInBackground() and then after you're done you can dismiss the dialog on the main thread in onPostExecute().

Now you can use:

new GetMostWanted(dialog).execute();

月下伊人醉 2024-10-26 06:57:25

@Amin 是正确的,解决问题的一个好方法是使用 AsyncTask,尽管他的实现不太适合您的需求。您可以在 onPreExecute() 中创建对话框,并在 onPostExecute() 中删除它。

您遇到的问题是,创建一个新的 Thread 然后调用 run 只会在 UI 线程上运行您的线程。对 getMostWanted() 的调用也会在 UI 线程中执行,并阻止对话框的创建。

因此,您的选择是像其他人建议的那样使用 AsyncTask,或者使用 ThreadHandler,其中 Handler code> 执行 UI 更新。

@Amin is correct that a good way to approach the problem is with an AsyncTask, although his implementation doesn't quite fit your needs. You would create your dialog in onPreExecute(), and remove it in onPostExecute().

The issue you are having is that creating a new Thread then calling run will just run your thread on the UI thread. Your call to getMostWanted() also executes in the UI thread, and blocks the creation of the dialog.

So your options are to use an AsyncTask as others have suggested, or to use a Thread and Handler, where the Handler performs the UI updates.

花开浅夏 2024-10-26 06:57:25

无法保证线程何时执行。我建议您改用 AsycTask。这是一个例子。然后您可以执行它并更新进度条。

 private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }

There is no guarantee when the thread is executed. I suggest you use an AsycTask instead. Here is an example. Then you can execute it and update your progressbar.

 private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }
佼人 2024-10-26 06:57:25

杰伊...如果你想使用线程和处理程序。将时间密集型任务放入可运行的方法中。创建“包含”可运行对象的线程并调用线程启动,以便时间密集型任务在单独的线程上运行。您应该能够在 UI 线程中启动该对话框。当后台线程完成并通知处理程序时,您应该能够关闭处理程序中绑定到 UI 线程的对话框。这是一些使用线程的代码。此代码片段在新线程中启动一个时间密集型进程。

buttonConfuseText.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        final String inString= editTextPlainText.getText().toString();
        Thread thread= new Thread( new Runnable() {
            public void run() {
                String outString= encrypt(password,inString); //<== time intensive task here
                Message msg= Message.obtain();
                Bundle b= new Bundle();
                b.putString("encryptedText",outString);
                msg.setData(b);
                handler.sendMessage(msg);
                Log.d(TAG,outString);
            }
        });
        thread.setDaemon(true);
        thread.start();
    }
});

您在这里等待线程完成:

public class ConfuseText extends Activity {
    private Handler handler= new Handler(){
        @Override
        public void  handleMessage(Message msg){
            super.handleMessage(msg);
            ConfuseText.this.onThreadMessage(msg); //<== close dialog here if you wish
        }
    };

public void onThreadMessage(Message msg){
    Bundle b= msg.getData();
    String encryptedText="";
    if (b != null){
        encryptedText= b.getString("encryptedText");
    }
    Log.d(TAG,encryptedText);
}

Jay... IF you want to use threads and handlers. Place the time intensive task into a runnable method. Create the thread "containing" the runnable object and call thread start so that the time intensive task is running on a separate thread. You should be able to launch the dialog in the UI thread. You should be able to dismiss the dialog in the handler, which is bound to the UI thread, when the background thread completes and notifies the handler. Here is some code using threads. This snippet launches a time intensive process in a new thread.

buttonConfuseText.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        final String inString= editTextPlainText.getText().toString();
        Thread thread= new Thread( new Runnable() {
            public void run() {
                String outString= encrypt(password,inString); //<== time intensive task here
                Message msg= Message.obtain();
                Bundle b= new Bundle();
                b.putString("encryptedText",outString);
                msg.setData(b);
                handler.sendMessage(msg);
                Log.d(TAG,outString);
            }
        });
        thread.setDaemon(true);
        thread.start();
    }
});

You wait for the thread to complete here:

public class ConfuseText extends Activity {
    private Handler handler= new Handler(){
        @Override
        public void  handleMessage(Message msg){
            super.handleMessage(msg);
            ConfuseText.this.onThreadMessage(msg); //<== close dialog here if you wish
        }
    };

public void onThreadMessage(Message msg){
    Bundle b= msg.getData();
    String encryptedText="";
    if (b != null){
        encryptedText= b.getString("encryptedText");
    }
    Log.d(TAG,encryptedText);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文