Renjith
Renjith

Reputation: 3617

Thread communication within the activity

I have an activity class as below.

public class LoginActivity extends Activity implements OnClickListener {
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      button1 = (ImageView) findViewById(R.id.button1);
      button1.setOnClickListener(this);
   }
   @Override
   public void onClick(View v) {
       loader = (ProgressBar) findViewById(R.id.loader);
       Thread processThread = new Thread(loaderThread); 
       loader.setVisibility(View.VISIBLE);
       processThread.start();

       try {
        Thread.currentThread().join();
        Log.i("Activity","gone past join()");
        loader.setVisibility(View.INVISIBLE);
   } catch (InterruptedException e) {
        e.printStackTrace();
   }
   }

  private Runnable loaderThread = new Runnable() {
 public void run() {
    ServiceCaller serviceCaller = new ServiceCaller();
    boolean status = serviceCaller.checkProcess(url);
  }
  };
}

Further Question [EDITED] Here is the scenario. The main activity class creates a thread on a click. The then created thread fetches some data from the server. It is a time consuming task. So a progress bar is displayed on the UI. Currently I am using AsyncTask (not shown here) to accomplish server data retrieval. But the real challenge is wait for the background task to complete and get the value from it. What I am looking for is:

wait until server calls are made and get the results. Meanwhile show the progress bar.

Any thoughts? Apologies in case I confuse you.

Thanks in advance!

Upvotes: 0

Views: 113

Answers (2)

ajmal
ajmal

Reputation: 4252

You must have a look at AsyncTask http://developer.android.com/reference/android/os/AsyncTask.html http://www.vogella.com/articles/AndroidPerformance/article.html

and you can show the ProgressBar in onPreExecute() do the task in doInBackground() and hide the ProgressBar in onPostExecute()

Upvotes: 2

nandeesh
nandeesh

Reputation: 24820

Join method blocks the current thread. In your case Onclick method is called in UI thread, so all UI operations are blocked. It is never a good idea to block Ui thread.

So you probably should use either a Handler or Asynctask to keep updating Progressbar

Upvotes: 1

Related Questions