【问题标题】:Only one Looper may be created per thread Error, Async Task每个线程只能创建一个 Looper 错误,异步任务
【发布时间】:2011-12-08 12:51:21
【问题描述】:

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

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

【问题讨论】:

    标签: android multithreading android-asynctask looper


    【解决方案1】:

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

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

    【讨论】:

    • 如果您尝试从 AsyncTask 内部更改 UI,请从 doInBackground 调用 publishProgress,然后在 onProgressUpdate 中进行更改。
    • 我能够以最小的麻烦从我的 doINBackground() 方法中获取所有 UI 内容,并且一切运行良好。非常感谢您的建议!
    猜你喜欢
    • 2016-03-19
    • 2012-01-16
    • 2011-04-22
    • 2014-05-27
    • 2019-05-05
    • 1970-01-01
    • 2019-01-22
    • 2016-01-16
    • 2018-05-09
    相关资源
    最近更新 更多