我想在点击按钮时停止此线程。
TIME_OUT = 45000;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent i = new
Intent(MapsActivity.this,MapsActivity.class);
startActivity(i);
finish();
}
}, TIME_OUT);
我在Activity的onCreate
中使用上面的处理程序。我想阻止它。如何在点击任何按钮或点击Back Pressed上时停止此线程?
答案 0 :(得分:4)
Handler handler = new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent i = new
Intent(MapsActivity.this,MapsActivity.class);
startActivity(i);
finish();
}
}, TIME_OUT);
然后您可以使用Handler#removeCallbacksAndMessages删除此回调或任何回调。
handler.removeCallbacksAndMessages(null);
答案 1 :(得分:2)
Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
Intent i = new
Intent(MapsActivity.this,MapsActivity.class);
startActivity(i);
finish();
}
};
handler.post(runnable);
// use this when you don't want callback to be called anymore
handler.removeCallbacks(runnable);
答案 2 :(得分:2)
好的最好的选择是使用布尔值作为那样的标志
TIME_OUT = 45000;
//add this boolean
boolean run =true;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
//run this method only when run is true
if(run==true){
//your code
}
}
}, TIME_OUT);
//on button click just change the boolean to flag and it will stop the run method
//on click
run=false;
答案 3 :(得分:2)
public class MainActivity extends Activity{
Handler handler;
Button b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
Intent i = new
Intent(MapsActivity.this,MapsActivity.class);
startActivity(i);
finish();
}
};
handler.post(runnable);
button1=(Button)findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
handler.removeCallbacks(handler);
}
});
}
}