java.lang.RuntimeException:每个线程只能创建一个Looper [英] java.lang.RuntimeException: Only one Looper may be created per thread

查看:390
本文介绍了java.lang.RuntimeException:每个线程只能创建一个Looper的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的线程,如下所示:

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();
  ...

编辑:添加可启动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 main activity, but inside of another thread that runs on the main activity.

无论如何,这个例子完全这里,但由于某种原因,它给了我java.lang.RuntimeException:每个线程只能创建一个Looper。

Anyway, this example is exactly the same as here, but for some reason it gives me java.lang.RuntimeException: Only one Looper may be created per thread.

我没有创造任何其他的弯曲,至少在任何地方都是如此。

I did not create any other loopers, at least explicitly anywhere.

推荐答案


java.lang.RuntimeException:每个线程只能创建一个Looper

java.lang.RuntimeException: Only one Looper may be created per thread

抛出异常是因为您(或核心Android代码)已经调用 Looper.prepare()对于当前正在执行的线程。

The exception is thrown because you (or core Android code) has already called Looper.prepare() for the current executing thread.

以下检查当前线程是否已存在Looper,如果不存在,则创建一个,从而避免 RuntimeException

The following checks whether a Looper already exists for the current thread, if not, it creates one, thereby avoiding the RuntimeException.

    public void run() 
    {
            if (Looper.myLooper() == null)
            {
              Looper.prepare();
            }
            thisHandler = new Handler();

         ....
    }

这篇关于java.lang.RuntimeException:每个线程只能创建一个Looper的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆