Devin Carpenter
Devin Carpenter

Reputation: 917

Android: How to have a background and UI thread run at the same time?

I need to have a network process running on a non-UI Thread and a UI thread running at the same time to inform the user that the process is running, and that the app isn't frozen, and won't allow the next block of code to be executed until the network connection gives its response.

What would the best way to go about doing this?

Upvotes: 0

Views: 99

Answers (1)

alenz316
alenz316

Reputation: 613

AsyncTasks are the way to go.

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

Upvotes: 3

Related Questions