无论如何停止线程android

时间:2014-02-24 20:39:07

标签: android multithreading

我有几个活动一个接一个点击按钮,但是如果按钮没有在10秒内点击,则下一个活动会在线程的帮助下自动启动。

button1 = (ImageButton)findViewById(R.id.button2);
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {

Intent firstIntent = new Intent(Tab1.this, Tab2.class);
startActivity(firstIntent);                 
            finish();
        }
    }); 

Thread background = new Thread() {
    public void run() {

     try {

     sleep(10*1000);


     Intent i=new Intent(getBaseContext(),Tab2.class);
     i.putExtra("CountNum", count);
     startActivity(i);

     finish();

     } catch (Exception e) {

            }
        }
    };

    background.start();

问题是:如果我从tab1转到tab2再转到tab3并点击按钮,那么10秒后tab2将再次启动,因为来自tab1的线程仍在运行(我不知道它是这样工作的= \)。怎么解决?如果我使用按钮,如何停止线程?提前致谢

2 个答案:

答案 0 :(得分:1)

有一段时间.stop()被弃用,因为它可能会以不安全的方式终止你的Thread

最常见的方法是在boolean内部设置Thread控制器,检查是否发生了某些操作(在您的情况下,按下了按钮),如果是,则在下一个循环迭代,只需在return中使用Thread即可。这将彻底和安全地终止它。

----编辑----

假设这是您的按钮onClickListener()

boolean has_been_clicked = false;

but = (ImageButton) findViewById(R.id.your_button_id);

but.setOnClickListener(new OnClickListener() {
  @Override
  public void onClick(View v) {
    // Do the stuff your need
    has_been_clicked = true;
  }
}); 

new Thread(
  new Runnable() { 
    public void run() { 
      while (!has_been_clicked) {
        // Do your stuff here...

        ...
      }
      // If you've reached this point, it means you have clicked
      // the button since the value of has_been_clicked is true,
      // start your Activity here
      ...
      startActivity(i);
      return;
    }
  }
).start();

答案 1 :(得分:0)

这是一个例子,我希望它能帮助我修改你的代码。

首先创建一个布尔OKToStart,它将用于检查我们是否在10秒内

button1 = (ImageButton)findViewById(R.id.button2);
boolean OKToStart =true;
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(OKToStart){
Intent firstIntent = new Intent(Tab1.this, Tab2.class);
startActivity(firstIntent);                 
            finish();
 }
        }
    }); 

Thread background = new Thread() {
    public void run() {
    while(OKToStart){

     try {

     sleep(10*1000);


     OKToStart =false



     } catch (Exception e) {

            }
        }
    }};

    background.start();
相关问题