消息队列Handler的用法

下面是每隔一段时间就执行某个操作,直到关闭定时操作:

final Handler handler = new Handler();
	     Runnable runnable = new Runnable(){
	         @Override
	         public void run() {
	             // TODO Auto-generated method stub
	             // 在此处添加执行的代码
	        	 secondImage.setVisibility(View.VISIBLE);
			     secondImage.startAnimation(inAnimation);
	            handler.postDelayed(this, 150);// 150是延时时长
	         } 
	     }; 
	     handler.postDelayed(runnable, 150);// 打开定时器,执行操作
	     handler.removeCallbacks(this);// 关闭定时器处理

下面是隔一段时间后执行某个操作一次,执行完后,不再执行

final Handler handler = new Handler();
		runCount = 0;// 全局变量,用于判断是否是第一次执行
		Runnable runnable = new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				if (runCount == 1) {// 第一次执行则关闭定时执行操作
					// 在此处添加执行的代码
					secondImage.setVisibility(View.VISIBLE);
					secondImage.startAnimation(inAnimation);
					handler.removeCallbacks(this);
				}
				handler.postDelayed(this, 150);
				runCount++;
			}

		};
		handler.postDelayed(runnable, 1000);// 打开定时器,执行操作
posted @ 2017-03-10 16:15  张亚楠  阅读(913)  评论(0编辑  收藏  举报