代码之家  ›  专栏  ›  技术社区  ›  Alex Hope O'Connor

Android 2.2:第二线程中的ProgressDialog冻结

  •  0
  • Alex Hope O'Connor  · 技术社区  · 14 年前

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

    这是课程: 公共类ProgressDialogThread扩展线程 { 公共活套螺纹活套; 公共处理程序mhandler;

    公共进程对话框线程加载; 公共上下文对话上下文; 公共字符串对话框标题; 公共字符串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();
    

    它会产生大量警告,有时甚至会导致一些崩溃:

    如。 处理程序:将消息发送到死线程….

    例外情况如 在……中 原因:按键发送时间结束

    谢谢你的帮助, 亚历克斯。

    1 回复  |  直到 14 年前
        1
  •  0
  •   Julian    14 年前

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

    谷歌搜索(或在堆栈溢出时搜索)也会提供关于如何使用它的大量信息。上面的链接还不够:)