如何停止Handler Runnable?

use*_*636 33 java performance multithreading android android-handler

我在以下程序中使用处理程序,我想在i = 5时停止它,但处理程序不会停止并连续运行.

   b1.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            handler = new Handler();
           runnable = new Runnable() {
                 public void run() {

                    try {
                        Toast.makeText(getApplicationContext(), "Handler is working", Toast.LENGTH_LONG).show();
                        System.out.print("Handler is working");

                       if(i==5){
                           //Thread.currentThread().interrupt();
                            handler.removeCallbacks(runnable);


                            System.out.print("ok");
                                        Toast.makeText(getApplicationContext(), "ok", Toast.LENGTH_LONG).show();
                        }
                       i++;
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } 
                   handler.postDelayed(this, 5000); 

               }
           };
           handler.postDelayed(runnable, 5000);
           //return;
        }
    });
Run Code Online (Sandbox Code Playgroud)

M-W*_*eEh 49

因为您postDelayed()在删除回拨后再次呼叫.请使用此代码:

final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
         public void run() {
               Log.d("Runnable","Handler is working");
               if(i == 5){ // just remove call backs
                    handler.removeCallbacks(this); 
                    Log.d("Runnable","ok");
                } else { // post again
                    i++;
                    handler.postDelayed(this, 5000); 
                }
       }
   };

//now somewhere in a method
 b1.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        handler.removeCallbacks(runnable); 
        handler.postDelayed(runnable, 5000); 
    }
});
Run Code Online (Sandbox Code Playgroud)


Ahm*_*kri 23

protected void onStop() {
    super.onStop();
    handler.removeCallbacks(runnable);
}
Run Code Online (Sandbox Code Playgroud)

你可以这样阻止它