2011-07-09 123 views
0

我想品牌的AsyncTask類做後臺更新調用者線程的進展,但調用者線程!=的UI線程。 我試過這段代碼,但行publishProgress(i)似乎沒有效果。 有人可以告訴我如何解決它(或者我可以使用其他類)。 在此先感謝=)Asynctask一個UI線程

public class MainUI extends Activity { 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     findViewById(R.id.button).setOnClickListener(new View.OnClickListener(){ 

      @Override 
      public void onClick(View v) { 
       Thread t=new Thread(){ 
        boolean exit=false; 
        public void run(){ 
         Looper.prepare(); 
         new DownloadFilesTask().execute(); 

         while (!exit){ 
          try { 
           Thread.sleep(600); 
          } catch (InterruptedException e) { 
           e.printStackTrace(); 
          } 
         } 

         Log.d("","Exit thread"); 

         Looper.loop(); 
        } 

        public void exit(){ 
         exit=true; 
        } 

        class DownloadFilesTask extends AsyncTask<Void, Long, Long> { 
         protected Long doInBackground(Void... urls) { 
          long i=0; 
          for (i=0;i<20;i++){ 
           Log.d("",i+" "); 
           try { 
            Thread.sleep(500); 
           } catch (InterruptedException e) { 
            e.printStackTrace(); 
           } 
           publishProgress(i); 
           } 
          return i; 
         } 
         protected void onProgressUpdate(Long... progress) { 
          Log.d("Test",progress[0]+""); 
             } 

             protected void onPostExecute(Long result) { 
              exit(); 
             } 
            } 


           }; 
           t.start(); 


          } 

         }); 
        } 





} 

回答

0

從Android文檔:

有必須遵循這一類工作的幾個線程規則正確:

必須在UI線程上創建任務實例。

execute(Params...) must be invoked on the UI thread. 
Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually. 
The task can be executed only once (an exception will be thrown if a second execution is attempted.) 

,所以你不能在UI線程之外創建它。改爲使用Task並將其包裝在ThreadPoolExecutor對象中。要知道,你需要使它線程安全使用其中的一個更新UI時:

Activity.runOnUiThread(Runnable) 
View.post(Runnable) 
View.postDelayed(Runnable, long) 

但再次的AsyncTask是無用的,我不建議這樣做。

問候

+0

來吧,當然的AsyncTask有它的用途。你只需要瞭解它是如何工作的,就像任何庫函數/類一樣。 – dhaag23