Wait for the inline thread to complete before proceeding to the next method

I have an Android app in which I do the following:

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(); } 

And I would like to make sure my thread is completed before stepTwo (); called. How can i do this?

Thanks!

+4
source share
3 answers

The Thread instance has a join method, so:

 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(); } 

You might want to try:

 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(); } 

Since onCreate is in the user interface thread, having a connection there will freeze the user interface until onCreate completes, retaining any dialog before. stepTwo will have to use SwingUtilities.invokeLater to make any changes to the user interface.

+2
source

If you want to run something in the background, I would recommend using the AsyncTask class , as this will ensure you interact with the UI correctly.

In addition, if you want the code to run after the background task completes, you can simply call this method. Inside onCreate() there is no reason to wait.

Your code will look something like this:

 @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(); } } 
+2
source

Another option is to simply move step2() to the thread so that it executes after the thread completes its tasks:

 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(); } 
+1
source

Source: https://habr.com/ru/post/1310172/


All Articles