当前位置 : 主页 > 手机开发 > android >

android – CalledFromWrongThreadException

来源:互联网 收集:自由互联 发布时间:2021-06-11
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final ThraedDemo objDemo = new ThraedDemo(); Thread objThread = new Thread() { @Override public void run() { objDemo.firstM
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    final ThraedDemo objDemo = new ThraedDemo();
    Thread objThread = new Thread() {

        @Override
        public void run() {

            objDemo.firstMethod();
        }
    };
    objThread.start();
}


class ThraedDemo {

        private void firstMethod() {
            Thread objThread = new Thread() {

                @Override
                public void run() {
                    try {
                    ((ImageView)findViewById(R.id.ImageViewnumber)).setImageResource(nums[n]);

                        Thread.sleep(10000);
                        Log.v("Thread","1111111111111111sleep");
                    } catch (InterruptedException ex) {
                        System.out.println("interuped exception" + ex.getMessage());
                    }
                    secondMethod();
                }

                private void secondMethod() {
        Thread objThread = new Thread() {

            @Override
            public void run() {
                try {
                ((ImageView)findViewById(R.id.ImageViewResult)).setImageResource(nums[n+1]);

                n++;

                    Thread.sleep(10000);
                   Log.v("Thread","22222222222 sleep");
                } catch (InterruptedException ex) {
                    System.out.println("interuped exception" + ex.getMessage());
                }
                firstMethod();
            }
        };
        objThread.start();
    }

            };
            objThread.start();
        }

    }

我使用上面的代码,但它没有运行.得到CalledFromWrongThreadException上面的代码有什么问题.请给我一些建议.谢谢你提前

我认为您不能从UI线程以外的其他线程查看修改,因此要么在oncreate中创建 handlers并将线程发布到它,要么使用 AsyncTask或 runOnUIThread方法将部分代码直接发送到UI线程.
网友评论