Android 2.2:ProgressDialog在第二个线程中冻结

时间:2010-10-17 11:43:43

标签: android multithreading progressdialog

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

这是班级: 公共类ProgressDialogThread扩展了Thread {  public Looper ThreadLooper;  public Handler mHandler;

public ProgressDialog ThreadDialog;  public Context DialogContext;  public String DialogTitle;  public String DialogMessage;

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

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

1 个答案:

答案 0 :(得分:0)

当想要在Android上的单独线程中执行操作时,您应该查看AsyncTask类。您可以在此处阅读:http://developer.android.com/resources/articles/painless-threading.html

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