[英]java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
[英]Can't create handler inside thread that has not called Looper.prepare() : java.lang.RuntimeException
我有以下代码在另一个线程中运行一个函数:
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。 请参阅“”中的“线程规则”部分,但这不是后台线程,而是从主活动中调用的。
请告诉我如何解决此问题。
Handler
类使用Looper
来执行其调度,并且刚创建的线程没有关联的循环器-因此出现错误。
由于您尚未提供处理程序创建代码,因此假设您要在主线程上调用代码。 在这种情况下,请按以下方式创建Handler
:
Handler handler = new Handler(Looper.getMainLooper());
计划在该Handler
上运行的任何内容都将在主Looper
上执行,该Looper
在主线程上运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.