CalledFromWrongThreadException

后端 未结 2 965
有刺的猬
有刺的猬 2020-11-29 12:23
 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    final ThraedDemo objDemo = new Thra         


        
相关标签:
2条回答
  • 2020-11-29 12:41

    I edited your 2nd function code, I see your code is loop forever cause the firstMethod call secondMethod and the secondMethod call the new firstMethod to start and then loop forever. I removed it and moved the code update ImageView into the UI Thread, could you try this:

    class ThraedDemo {
    
        private void firstMethod() {
            Thread objThread = new Thread() {
                @Override
                public void run() {
                    try {
                        runOnUiThread(new Runnable() {
                            public void run(){ 
                                ((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();
                }
            };
            objThread.start();
        }
    
        private void secondMethod() {
            Thread objThread2 = new Thread() {
    
                @Override
                public void run() {
                    try {
                        runOnUiThread(new Runnable() {
                            public void run(){ 
                                ((ImageView)findViewById(R.id.ImageViewnumber)).setImageResource(nums[n+1]);  
                            }
                        });
                        n++;
                        Thread.sleep(10000);
                        Log.v("Thread","22222222222 sleep");
                    } catch (InterruptedException ex) {
                        System.out.println("interuped exception" + ex.getMessage());
                    }
                }
            };
            objThread2.start();
        }
    }
    
    0 讨论(0)
  • 2020-11-29 12:48

    I think you can't do view modifications from another thread than the UI thread, so either create handlers in the oncreate and post your thread to it, or use AsyncTask, or runOnUIThread method to send portions of code directly to the UI thread.

    0 讨论(0)
提交回复
热议问题