2012-05-02 119 views
0

我有更改屏幕颜色的代码。在Android上停止线程

但我不知道如何停止这个线程:

lin = (LinearLayout)findViewById(R.id.mainlayout); 
     new Thread(new Runnable() { 
      public void run() { 
       while (finalStatus < 1) { 
        try { 
         Thread.sleep(500); 
        } catch (InterruptedException e) { 
         e.printStackTrace(); 
        } 
        colorHandler.post(new Runnable() { 
         public void run() { 
          if(flag) 
          { 
          lin.setBackgroundColor(Color.BLUE); 
          flag = false; 
          } 
          else 
          { 
           lin.setBackgroundColor(Color.RED); 
           flag = true; 
          } 
         } 
        }); 
       } 
      } 
     }).start(); 

我试图把:

Button btn = (Button) findViewById(R.id.button1); 
     btn.setOnClickListener(new View.OnClickListener() 
     { 
      public void onClick(View v) 
      { 
       Toast.makeText(getBaseContext(),"STOP",Toast.LENGTH_SHORT).show(); 
       finalStatus=1; 
       lin.setBackgroundColor(Color.BLACK); 
      } 
     }); 

和线程停止,但屏幕为红色,或蓝色的,我需要黑色。

此外,如何启动这个线程后,我已经停止了它?

+1

那里没有服务,只有一些线程。如果你想离开,只需将finalStatus更改为一个。有什么我失踪了吗?更新背景的代码没有任何循环,因此会立即结束。 – azertiti

+0

谢谢,看我的编辑 – Gold

+0

看到我的答案吼叫。 – azertiti

回答

0

我不确定获取背景蓝色或红色的场景是什么,但让我们假设它是当您将finalStatus设置为1时。为了避免更改背景并仍然退出线程,您可以将其设置为不同在您按一下按钮听众价值,让我们给111说添加以下条件之前colorHandler.post将解决这一问题:

if (finalStatus == 111) { 
    return; 
} 
0

就放进了外螺纹的run()方法后while循环lin.setBackgroundColor(Color.BLACK);代码。并且不要忘记使用相同的处理程序,因为UI线程不会更新UI。

+0

这会产生意想不到的效果。第一个是你不知道哪个线程会先运行 - 将背景设置为黑色或不同的颜色。根据执行顺序,其中一个总是被覆盖。 – azertiti