首页 > 代码库 > Android处理延时加载的方法

Android处理延时加载的方法

在项目开发中,经常需要通过延时加载来实现满足我们的项目要求。那到底怎样来实现延时,下面结合java与android的相关方法来实现延时问题。


一.利用线程的Sleep方法

<span style="font-family:Microsoft YaHei;font-size:18px;"><span style="white-space:pre">		</span>new Thread(new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					Thread.sleep(1000);
					myHandler.sendEmptyMessage(what);//处理主线程方法
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});</span>

二. 利用Timer和TimerTask延时器

<span style="font-family:Microsoft YaHei;font-size:18px;"><span style="white-space:pre">		</span>// 1.实例化Timer
		Timer timer = new Timer();
		// 2.实例化TimerTask
		TimerTask timerTask = new TimerTask() {

			@Override
			public void run() {
				// TODO Auto-generated method stub

			}
		};
		// 3.启动定时器
		/**
		 * task: the task to schedule. 
		 * delay: amount of time in milliseconds before first execution. 
		 * period: amount of time in milliseconds between subsequent executions
		 */
		timer.schedule(timerTask, delay, period);

		// 4.关闭定时器
		if (timerTask != null) {
			timerTask.cancel();
			timerTask = null;
		}

		// 5.重新开启定时器,需要重新实例化

		timerTask = new TimerTask() {

			@Override
			public void run() {
				// TODO Auto-generated method stub

			}
		};
		timer.schedule(timerTask, delay, period);</span>
3.利用android自带的Handler消息处理

<span style="font-family:Microsoft YaHei;font-size:18px;">		/**
		 * delayMillis:The delay (in milliseconds) until the Runnable will be executed.
		 */
		new Handler().postDelayed(new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				
			}
			
		}, delayMillis);</span>
4.SchduleExecutorService接口处理延时 迭代

<span style="font-family:Microsoft YaHei;font-size:18px;"><span style="white-space:pre">		</span>/**
		 * ScheduledExecutorService提供了按时间安排执行任务的功能,它提供的方法主要有:
		 * schedule(task,initDelay):安排所提交的Callable或Runnable任务在initDelay指定的时间后执行。
		 * scheduleAtFixedRate():安排所提交的Runnable任务按指定的间隔重复执行
		 * scheduleWithFixedDelay():安排所提交的Runnable任务在每次执行完后,等待delay所指定的时间后重复执行。
		 * 
		 * initialDelay: the time to delay first execution
		 * period: the period between successive executions
		 * unit: the time unit of the initialDelay and period parameters
		 */
		//1.实例化
		ScheduledExecutorService schedule = Executors.newScheduledThreadPool(2);
		//2.开启定时 循环迭代处理
		schedule.scheduleAtFixedRate(new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				
			}
			
		}, initialDelay, period, unit);
		//3.关闭
		if(schedule != null){
			schedule.shutdown();
			schedule = null;
		}</span>