0

我想在按钮单击时停止此线程。

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);

我在onCreateActivity 中使用上述处理程序。我想阻止它。如何在单击任何按钮或单击 Back Pressed 时停止该线程?

4

4 回答 4

6
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);
于 2017-11-04T09:53:50.377 回答
3

好的,最好的选择是使用布尔值作为这样的标志

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;
于 2017-11-04T09:58:56.340 回答
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(runnable);  
            }  
        });  

   
}


 
}
于 2017-11-04T11:05:48.440 回答
1
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);
于 2017-11-04T09:54:32.643 回答