Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know that a thread is finished [duplicate]

Tags:

android

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.

like image 829
swati Avatar asked Dec 20 '22 17:12

swati


2 Answers

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");
 }
}
like image 172
Richard Lewin Avatar answered Jan 06 '23 14:01

Richard Lewin


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

like image 31
Laurent Perrin Avatar answered Jan 06 '23 13:01

Laurent Perrin