【问题标题】:Can't create handler inside thread that has not called Looper.prepare() : java.lang.RuntimeException无法在未调用 Looper.prepare() 的线程内创建处理程序:java.lang.RuntimeException
【发布时间】:2013-11-13 22:05:29
【问题描述】:

我有以下代码在另一个线程中运行一个函数:

Button buttonb = (Button) this.findViewById(R.id.buttonb);
    buttonb.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

        …
                progressBar.setVisibility(View.VISIBLE);

                Thread thread = new Thread() {
                    @Override
                    public void run() {
                        matrixOperation(sourcePhoto);
                    }
                };
                thread.start();

                progressBar.setVisibility(View.INVISIBLE);
        …

        }
    });

但在运行时我收到此错误:

Can't create handler inside thread that has not called Looper.prepare()

我搜索并发现此错误的一个原因是“您无法从后台线程执行 AsyncTask。请参阅“但这不是后台线程”的“线程规则”部分,我从我的主活动中调用它。

请告诉我如何解决这个问题。

【问题讨论】:

  • 你正在开始一个话题。所以它在后台线程中运行。
  • matrixOperation() 是做什么的?

标签: java android multithreading


【解决方案1】:

Handler 类使用Loopers 来执行其调度,并且刚刚创建的线程没有关联的循环器——因此会出现错误。

由于您没有提供处理程序创建代码,我假设您想在主线程上调用代码。在这种情况下,创建Handler,如下所示:

Handler handler = new Handler(Looper.getMainLooper());

任何计划在该Handler 上运行的东西都将在主Looper 上执行,该主线程在主线程上运行。

【讨论】:

  • 如何使用handler 对象?
  • 只需将Runnable 传递给它的post 方法
猜你喜欢
  • 1970-01-01
  • 2013-06-27
  • 2019-06-04
  • 1970-01-01
相关资源
最近更新 更多