Android:如何同时运行后台和UI线程?

时间:2015-05-14 21:11:53

标签: android multithreading

我需要在非UI线程和同时运行的UI线程上运行网络进程,以通知用户该进程正在运行,并且该应用程序未被冻结,并赢得&# 39; t允许执行下一个代码块,直到网络连接给出响应。

这样做最好的方法是什么?

1 个答案:

答案 0 :(得分:3)

AsyncTasks是要走的路。

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