Handler将Runnable放入线程队列,removecallback()移除Runnable

下面是小demO

public class MainActivity extends Activity {
	
    private Handler handler;
    private Runnable runnable;
    private int i=0;
    private Button button1;
    private Button button2;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		button1=(Button)this.findViewById(R.id.button1);
		button2=(Button)this.findViewById(R.id.button2);
		handler =new Handler();
		
		button1.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				handler.post(runnable);
			}
		});
		
		button2.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				//将runnable从线程队列移除
				handler.removeCallbacks(runnable);
			}
		});
		
		runnable=new Runnable() {
			@Override
			public void run() {
				 Log.e("---------------i的值是---------------", ""+(++i));  
				 handler.postDelayed(runnable, 1000); //每隔一秒执行一次 
			}
		};
		
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		//将runnable从线程队列移除
		handler.removeCallbacks(runnable);
	}

}


 

你可能感兴趣的:(<,java,多,线,程,>)