获取java.lang.IllegalStateException:当前线程必须有一个looper

时间:2015-04-16 16:29:29

标签: android performance android-asynctask android-looper

我收到此错误,我的应用程序崩溃了:

  

java.lang.IllegalStateException:当前线程必须有一个looper!

我没有太多关于如何在Google上使用looper,我使用线程(主要用于睡眠功能),处理程序(用于在Async任务运行时下载图像)和Async任务(用于获取JSON)来自URL的数据)。我不知道如何解决这个问题,所以任何建议都会有所帮助。

这是单击按钮时执行的线程代码:

View view = flingContainer.getSelectedView();
          view.findViewById(R.id.item_swipe_right_indicator).setAlpha((float) 1.0);

        Thread timer = new Thread() {
            public void run() {
                try {
                    sleep(320);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    flingContainer.getTopCardListener().selectLeft();
                }
            }
        };
        timer.start();

我正在使用this libray和log-cat是: image

其中:log {cat中的最后一个at com.enormous.quotesgram.MainActivity$3.run(MainActivity.java:479)对应于上面代码段中的行flingContainer.getTopCardListener().selectLeft();

1 个答案:

答案 0 :(得分:1)

尝试以下操作(遗憾的是我无法测试代码):

Thread timer = new Thread() {
    public void run() {
        try {
            sleep(320);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    flingContainer.getTopCardListener().selectLeft();
                }
            });
        }
    }
};

背后的想法是,Timer线程一个Looper线程(导致异常说"当前线程必须有一个笨蛋" )。然而,UI线程是Looper线程(例如参见this site)。

由于flingContainer.getTopCardListener().selectLeft()可能被设计为在UI线程上运行,如果它没有在流水线线程的一侧调用,它就会失败。