2011-10-15 21 views
1

本帖子底部的代碼由以下代碼行觸發。每個線程只能創建一個Looper錯誤,異步任務

new MasterClickAsyncTask(main).execute(position); 

以下代碼的doInBackground部分調用一個包含for循環的方法,因此需要Looper.prepare()。

此代碼細運行第幾次它被稱爲但然後引發以下錯誤:

10-15 22:50:24.752:ERROR/AndroidRuntime(9258):java.lang中:通過引起的。 RuntimeException:每個線程只能創建一個Looper。

我試過把Looper.getMainLooper()。以及AsyncTask各個部分中的其他一些內容,但這只是使其立即崩潰。

任何幫助?

代碼:

import java.io.IOException; 
import java.net.MalformedURLException; 
import org.json.JSONException; 
import android.os.AsyncTask; 
import android.os.Looper; 
import android.view.View; 

public class MasterClickAsyncTask extends AsyncTask<Integer, Void, Void> { 

    Master selectedMaster; 
Main main; 
MasterGridView masterGridView; 
Integer i; 
DiscogProxy discogProxy = new DiscogProxy(); 

MasterClickAsyncTask(Main main){ 
    this.main = main; 
    this.masterGridView = main.getMasterGridView(); 
} 

@Override 
    protected void onPreExecute() { 
     main.progressBar.setVisibility(View.VISIBLE); 
    } 
     @Override 
     protected Void doInBackground(Integer... params) { 
      masterGridView.getSelectedView(); 
      Globals.selectedMaster = (Master)(masterGridView).getItemAtPosition(params[0].intValue()); 
      Globals.selectedMaster.getVersionListView().getVersionList().clear(); 
       Looper.prepare(); 
       try { 
        Globals.selectedMaster.getVersionListView().populateVersionList(); 
       } catch (MalformedURLException e) { 
        e.printStackTrace(); 
       } catch (JSONException e) { 
        e.printStackTrace(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
       //Looper.getMainLooper().quit(); 
     return null;  
     }  

@Override 
protected void onPostExecute(Void result) { 
    main.populateAlbumVersionsView(); 
    main.progressBar.setVisibility(View.GONE); 
} 
} 

回答

4

尺蠖無關與循環。 Looper是控制UI線程的Android系統的一部分。有幾件事情在沒有準備活套的情況下無法正常工作,但通常最好避免使用Looper.prepare();除非是絕對的底色。使用異步doInBackground執行數據處理或其他更長時間的操作會更好,然後使用onPostExecute和onProgressUpdate更新UI。

總之,除非以某種方式使用UI,否則不需要調用Looper。如果您發現自己必須調用Looper,則可能需要重構後臺線程的工作方式。

+3

如果您嘗試從AsyncTask中更改UI,請從doInBackground調用publishProgress,然後在onProgressUpdate中執行更改。 – H9kDroid

+0

我能夠用最少的大驚小怪取得我的doINBackground()方法中的所有UI東西,並且它運行良好。非常感謝您的建議! –