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>




版权声明:本文博主原创文章,博客,未经同意不得转载。

原文地址:https://www.cnblogs.com/zfyouxi/p/4831888.html