4

I have an activity in which i am running a thread to hit the web service.i want to finish the activity only when the thread is finished.

swati
  • 1,263
  • 2
  • 17
  • 27
  • 1
    why don't you simply finish your activity as the last statement in the Thread which obviously gets executed only at the last. – Andro Selva Aug 07 '12 at 08:52
  • @Andro Selva I tried but the activity is finished first and the thread is running in the background – swati Aug 07 '12 at 08:57

3 Answers3

7

To make your life easier use Android AsyncTask Object. This provides the same background process as a Thread but handles everything for you. This includes callbacks at different stages of the AsyncTask. This includes once it has finished doing what you ask of it in the background via the onPostExecute() function.

From the documentation:

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
 protected Long doInBackground(URL... urls) {
     int count = urls.length;
     long totalSize = 0;
     for (int i = 0; i < count; i++) {
         totalSize += Downloader.downloadFile(urls[i]);
         publishProgress((int) ((i / (float) count) * 100));
         // Escape early if cancel() is called
         if (isCancelled()) break;
     }
     return totalSize;
 }

 protected void onProgressUpdate(Integer... progress) {
     setProgressPercent(progress[0]);
 }

 protected void onPostExecute(Long result) {
     showDialog("Downloaded " + result + " bytes");
 }
}
Richard Lewin
  • 1,870
  • 1
  • 19
  • 26
  • `ASyncTask` are good but the question is about knowing when a thread finishes, which is possible so no need to find a workaround. – shkschneider Aug 07 '12 at 09:08
  • @shkschneider - onPostExecute happens at the end of the Async thread. So, nothing prevents you from notifying the main thread that the thread has finished in there. – Eugene Kartoyev Aug 18 '20 at 20:43
4

You can use Thread.join(), which works for all Java programs (not just Android).

Laurent Perrin
  • 14,671
  • 5
  • 50
  • 49
0

You can call isAlive() method of your Thread or getStatus() if you use AsyncTask

Saasha
  • 277
  • 1
  • 2
  • 8