2010-05-18 29 views
4

我有一个Android应用程序在那里我做之前完成以下步骤:等待直列线程移动到下一个方法

private void onCreate() { 
    final ProgressDialog dialog = ProgressDialog.show(this, "Please wait..", "Doing stuff..", true); 

    new Thread() { 
     public void run() { 
      //do some serious stuff... 
      dialog.dismiss();   
     } 
    }.start(); 

    stepTwo(); 
} 

而且我想确保我的线程完成stepTwo前();叫做。我怎样才能做到这一点?

谢谢!

+0

可能是你可以使用isAlive – 2014-06-17 18:40:38

回答

2

线程实例有一个join方法,那么:

private void onCreate() { 
    final ProgressDialog dialog = ProgressDialog.show(this, "Please wait..", "Doing stuff..", true); 

    Thread t = new Thread() { 
     public void run() { 
      //do some serious stuff... 
      dialog.dismiss();   
     } 
    }; 
    t.start(); 
    t.join(); 
    stepTwo(); 

} 

你可能想,虽然试试这个:

private void onCreate() { 
    final ProgressDialog dialog = ProgressDialog.show(this, "Please wait..", "Doing stuff..", true); 

    Thread t = new Thread() { 
     public void run() { 
      //do some serious stuff... 
      SwingUtilities,invokeLater(new Runnable() { 
       public void run() { 
        dialog.dismiss();   
       } 
      }); 
      stepTwo(); 
     } 
    }; 
    t.start(); 
} 

因为的onCreate是在UI线程,具有会有联接冻结UI直到onCreate完成后,保存任何对话框。 stepTwo将不得不使用SwingUtilities.invokeLater自己做任何UI更改。

+1

如果我没有弄错,'dialog.dismis()'应该发生在UI线程中。 – aioobe 2010-05-18 21:05:09

+0

@aioobe - 我希望你是对的。这就是SwingUtilities.invokeLater的用途。除非Android是不同的 – sblundy 2010-05-18 21:12:12

+0

谢谢sblundy - 这是工作的大部分,但我的对话不出现,因为我相信它应该。基本上会发生的是它看起来正确地执行了线程中的任务,然后调用stepTwo();然后对话框出现一瞬间并消失。任何想法如何让它显示在它开始线程之前? – Tyler 2010-05-18 21:24:00

2

如果你想在后台运行,我建议使用the AsyncTask class,这样可以确保你能够正确地与UI线程交互。另外,如果您希望代码在后台任务完成后运行,那么您可以直接调用该方法。 onCreate()内没有理由等待。

您的代码将是这个样子:

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    new MyAsyncTask().execute(); 
} 

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

    @Override 
    protected void onPreExecute() { 
     dialog = ProgressDialog.show(MyActivity.this, "Please wait..", "Doing stuff..", true); 
    } 

    @Override 
    protected Void doInBackground(Void... params) { 
     //do some serious stuff... 
     return null; 
    } 

    @Override 
    protected void onPostExecute(Void result) { 
     dialog.dismiss(); 
     stepTwo(); 
    } 

} 
1

另外,选择是简单地移动step2()到线程,以便之后线程任务完成执行:

private void onCreate() { 
    final ProgressDialog dialog = ProgressDialog.show(this, "Please wait..", "Doing stuff..", true); 

    new Thread() { 
     public void run() { 
      //do some serious stuff... 
      dialog.dismiss();   
      stepTwo(); 
     } 
    }.start(); 
} 
+0

如果'stepTwo()'不需要在UI线程上运行,这只是一个选项 – 2014-07-11 09:49:04

相关问题