当前位置: 代码迷 >> Android >> android 程序中 常常用到的几种定时器
  详细解决方案

android 程序中 常常用到的几种定时器

热度:93   发布时间:2016-04-28 07:35:00.0
android 程序中 经常用到的几种定时器

上片说到了 需要用1个 定时器去 动态的绘制。

定时器 - 也就是个   你设置了时间  比如 3秒重复1个操作, 那么当你设置好 开启后, “他” 就会帮你完成这个重复任务,除非各种情况制止“他”停止


  /**     * alarm -  这个能保持程序一直处于唤醒的状态 也就是说  拔出USB  待机 等     */	{		AlarmManager  alarmManager = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);			//PendingIntent  pending = PendingIntent.getActivities(context, requestCode, intents, flags) 		//PendingIntent  pending = PendingIntent.getActivity(context, requestCode, intent, flags)  		//PendingIntent  pending = PendingIntent.getBroadcast(context, requestCode, intent, flags)		//PendingIntent  pending = PendingIntent.getService(context, requestCode, intent, flags)				//PendingIntent  pending = PendingIntent.writePendingIntentOrNullToParcel(sender, out)		//PendingIntent  pending = PendingIntent.readPendingIntentOrNullFromParcel(in)				//在指定的延时后,发送,但是不唤醒设备		int type1 = AlarmManager.ELAPSED_REALTIME;		//在指定的延时后   发送 并唤醒设备(常用)	    int type2 =AlarmManager.ELAPSED_REALTIME_WAKEUP;	    //在指定的时刻  发送 并唤醒设备	    int type3 =AlarmManager.RTC;	    //在指定的时刻   发送   唤醒设备	    int type4 =AlarmManager.RTC_WAKEUP;				//alarmManager.set(type, triggerAtMillis, operation)    发送1次		//alarmManager.setRepeating(type, triggerAtMillis, intervalMillis, operation); 重复发送			}			/**	 *   上面的alarm是可以保持 程序处于唤醒状态的。	 *   下面的并没有, 所以当手机拔出 USB 和 屏幕处于待机状态一会后,可能是会出现问题的,比如10分钟联网发送一次数据	 *   当然这个也是可以解决的,下篇文章说明	 * 	 */			/**	 * timer - 定时器	 */	{		Timer time = new Timer();		TimerTask timeTask = new TimerTask(){			@Override			public void run() {			    //执行你自己的操作				}		};				int  wait_time = 1000;    //等待1秒后开始		int  repeate_time= 2000;  //重复频率为 2秒		time.schedule(timeTask, wait_time, repeate_time);				//time.scheduleAtFixedRate(task, when, period)			}			/**	 * 线程定时器	 */	{		Thread th  = new Thread(){			@Override			public void run() {				try {					 while(true){						 //执行你的操作						 //更新UI						 han.post(new Runnable() {							@Override							public void run() {								// TODO Auto-generated method stub															}						}); 						 						 						 thread.sleep(3000);					 }				} catch (Exception e) {				}			}			};						Thread th1  = new Thread(){			@Override			public void run() {				try {					 while(true){						 //执行你的操作						 //更新UI						 han.sendMessage(new Message());						 thread.sleep(3000);					 }				} catch (Exception e) {				}			}			};								Thread th2  = new Thread(){			@Override			public void run() {				try {					 while(true){				         han.postDelayed(new Runnable() {							@Override							public void run() {								//执行你的操作							}						}, 3000);											 }				} catch (Exception e) {				}			}			    };		  }


  相关解决方案