0

我最近尝试创建一种在第二个线程中打开 ProgressDialog 的简单方法,因此如果主线程冻结,对话框将继续工作。

这是类: public class ProgressDialogThread extends Thread { public Looper ThreadLooper; 公共处理程序 mHandler;

公共 ProgressDialog 线程对话框;公共上下文对话上下文;公共字符串对话框标题;公共字符串对话框消息;

public ProgressDialogThread(Context mContext, String mTitle, String mMessage)
 {
  DialogContext = mContext;
  DialogTitle = mTitle;
  DialogMessage = mMessage;
 }

 public void run()
 {
  Looper.prepare();
  ThreadLooper = Looper.myLooper();

  ThreadDialog = new ProgressDialog(DialogContext);
  ThreadDialog.setTitle(DialogTitle);
  ThreadDialog.setMessage(DialogMessage);
  ThreadDialog.show();

  mHandler = new Handler();

  Looper.loop();
 }

 public void Update(final String mTitle, final String mMessage)
 {
  while(mHandler == null)
   synchronized(this) {
    try { wait(10); } 
    catch (InterruptedException e) {
     Log.d("Exception(ProgressDialogThread.Update)", e.getMessage() == null ? "MISSING MESSAGE" : e.getMessage());
    }
   }

  mHandler.post(new Runnable(){
   @Override
   public void run() {
    ThreadDialog.setTitle(mTitle);
    ThreadDialog.setMessage(mMessage);
   }});
 }

 public void Dismiss() 
 {
  while(ThreadDialog == null || mHandler == null)
   synchronized(this) {
    try { wait(10); } 
    catch (InterruptedException e) {
     Log.d("Exception(ProgressDialogThread.Dismiss)", e.getMessage() == null ? "MISSING MESSAGE" : e.getMessage());
    }
   }

  mHandler.post(new Runnable(){
   @Override
   public void run() {
    ThreadDialog.dismiss();
   }});
 }

 public void Continue() 
 {
  while(ThreadLooper == null || mHandler == null)
   synchronized(this) {
    try { wait(10); } 
    catch (InterruptedException e) {
     Log.d("Exception(ProgressDialogThread.Continue)", e.getMessage() == null ? "MISSING MESSAGE" : e.getMessage());
    }
   }

  mHandler.post(new Runnable(){
   @Override
   public void run() {
    ThreadLooper.quit();
   }});
 }

然而,它有时可以完美运行,但有时应用程序最终会冻结并崩溃。

这是一个使用示例:

ProgressDialogThread thread = new ProgressDialogThread(this, "Loading", "Please wait...");
thread.start();
// Do Stuff
thread.Dismiss();
thread.Continue();

它有时会产生很多警告甚至崩溃:

例如。处理程序:向死线程发送消息....

以及诸如 ANR 之类的异常......原因:keyDispatchingTimedOut

感谢您的帮助,亚历克斯。

4

1 回答 1

0

当你想在 Android 上的不同线程中做事时,你应该看看这个AsyncTask类。你可以在这里阅读:http: //developer.android.com/resources/articles/painless-threading.html

谷歌搜索(或在 Stack Overflow 上搜索)也会为您提供有关如何使用它的大量信息,上面的链接还不够:)

于 2010-10-17T13:44:06.360 回答