java.lang.RuntimeException:每个线程只能创建一个 Looper
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23038682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java.lang.RuntimeException: Only one Looper may be created per thread
提问by user3081519
I have a simple thread that goes like this:
我有一个简单的线程,如下所示:
public class AwesomeRunnable extends Thread {
Handler thisHandler = null;
Handler uihandler = null;
String update = null;
long time = 0;
public AwesomeRunnable(Handler h, long howLong) {
uihandler = h;
time = howLong;
}
public void run() {
Looper.prepare();
thisHandler = new Handler();
...
EDIT: ADDED CODE THAT STARTS THE RUNNABLE
编辑:添加了启动 RUNNABLE 的代码
public class StartCycle implements Runnable {
@Override
public void run() {
pomodoroLeft = numPomodoro;
while(pomodoroLeft > 0) {
pomodoroLeft--;
actualSeconds = 6 * ONE_SECOND;
runnable = new AwesomeRunnable(myHandler, actualSeconds);
runnable.start();
waitForClock();
It is an inner class of a main activity. This thread, however runs not on the mainactivity, but inside of another thread that runson the mainactivity.
它是一个主要活动的内部类。这个线程,但运行不上主要的活动,但内部的另一个线程运行的主要活动。
Anyway, this example is exactlythe same as here, but for some reason it gives me java.lang.RuntimeException: Only one Looper may be created per thread.
不管怎样,这个例子和这里的完全一样,但由于某种原因它给了我 java.lang.RuntimeException:每个线程只能创建一个 Looper。
I did not create any other loopers, at least explicitly anywhere.
我没有创建任何其他循环器,至少在任何地方都没有明确创建。
采纳答案by Aown Raza
java.lang.RuntimeException: Only one Looper may be created per thread
java.lang.RuntimeException:每个线程只能创建一个 Looper
The exception is thrown because you (or core Android code) has already called Looper.prepare()
for the current executing thread.
抛出异常是因为您(或核心 Android 代码)已经调用Looper.prepare()
了当前正在执行的线程。
The following checks whether a Looper already exists for the current thread, if not, it creates one, thereby avoiding the RuntimeException
.
下面检查当前线程是否已经存在 Looper,如果不存在,则创建一个 Looper,从而避免RuntimeException
.
public void run()
{
if (Looper.myLooper() == null)
{
Looper.prepare();
}
thisHandler = new Handler();
....
}
回答by XPscode
Instead of just calling Looper.prepare();
, first check if Looper
does not already exist for your Thread
, if not, call that function. Like this:
而不是仅仅调用Looper.prepare();
,首先检查您的 是否Looper
不存在Thread
,如果不存在,则调用该函数。像这样:
if (Looper.myLooper()==null)
Looper.prepare();