android - 每个线程只能创建一个 Looper 错误,异步任务

标签 android multithreading android-asynctask looper

本文底部的代码由以下代码行触发。

new MasterClickAsyncTask(main).execute(position);

下面代码的 doInBackground 部分调用了一个包含 for 循环的方法,因此需要 Looper.prepare()。

此代码在调用前几次运行良好,但随后抛出以下错误:

10-15 22:50:24.752: ERROR/AndroidRuntime(9258): Caused by: java.lang.RuntimeException: 每个线程只能创建一个 Looper

我试过将 Looper.getMainLooper().quit();在 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);
}   
}

最佳答案

Looper 与 for 循环无关。 Looper 是 Android 系统中控制 UI 线程的部分。如果没有准备循环器,有几件事将无法工作,但一般来说,除非绝对必要,否则最好避免使用 Looper.prepare();。最好使用异步 doInBackground 执行数据处理或其他更长的操作,然后使用 onPostExecuteonProgressUpdate 更新 UI。

简而言之,除非您以某种方式使用 UI,否则不需要调用 Looper。如果您发现自己必须调用 Looper,您可能需要重构后台线程的工作方式。

关于android - 每个线程只能创建一个 Looper 错误,异步任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7781230/

相关文章:

Android AudioRecord频率过滤器一步一步

Android:TabActivity - 在 AsyncTask 完成之前不添加标签

Android TextView 未设置

android - FFMpeg 文本动画

java - 在没有互联网连接到 Wifi 时使用蜂窝数据

c++ - 独立、操作系统无关、架构中立、多线程库

objective-c - 从多个线程使用 runModalForWindow 有多危险?

java - JSON 解析为 ArrayList。如何让它在 onPostExecute 中重复多个 map 标记的数据?

android - 如何将我的图像传递到 facebook 提要对话框 android

c++ - 如果一个线程在关键部分调用 Acquire(),如果另一个线程调用 Release(),该锁是否会被释放?