2011-10-15 23 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东西,并且它运行良好。非常感谢您的建议! –