Android 定时器大全

在Android上常用的定时器有两种,一种是Java.util.Timer,一种就是系统的AlarmService了。

实验1:使用Java.util.Timer。
在onStart()创创建Timer,每5秒更新一次计数器,并启动。

Java代码 复制代码 收藏代码
  1. mTimer = new Timer();
  2. mTimer.schedule(new TimerTask() {
  3. @Override
  4. public void run() {
  5. ++mCount;
  6. mHandler.sendEmptyMessage(0);
  7. }
  8. }, 5*1000, 5*1000);
mTimer = new Timer();        
mTimer.schedule(new TimerTask() {
            @Override
            public void run() { 
                ++mCount; 
                mHandler.sendEmptyMessage(0);                
            } 
        }, 5*1000, 5*1000); 

当连接USB线进行调试时,会发现一切工作正常,每5秒更新一次界面,即使是按下电源键,仍然会5秒触发一次。
当拔掉USB线,按下电源键关闭屏幕后,过一段时间再打开,发现定时器明显没有继续计数,停留在了关闭电源键时的数字。

实验2:使用AlarmService每隔5秒发送一个广播:
2.1,设置setRepeating()的类型为AlarmManager.ELAPSED_REALTIME的情况
Java代码 复制代码 收藏代码
  1. AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
  2. am.setRepeating(AlarmManager.ELAPSED_REALTIME,firstTime,5*1000,sender);
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);   
am.setRepeating(AlarmManager.ELAPSED_REALTIME,firstTime,5*1000,sender);

拔掉USB线,按下电源键,过一段时间再次打开屏幕,发现定时器没有继续计数。
2.2,设置setRepeating()的类型为AlarmManager.ELAPSED_REALTIME_WAKEUP的情况
Java代码 复制代码 收藏代码
  1. AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
  2. am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, 5*1000, sender);
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);    
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, 5*1000, sender);

拔掉USB线,按下电源键,过一点时间再次打开屏幕,发现定时器一直在计数。

如此看来,使用WAKEUP才能保证自己想要的定时器一直工作,但是肯定会引起耗电量的增加。

http://www.cnblogs.com/jico/archive/2010/11/03/1868361.html
AlarmManager的使用机制有的称呼为全局定时器,有的称呼为闹钟。通过对它的使用,个人觉得叫全局定时器比较合适,其实它的作用和Timer有点相似。都有两种相似的用法:(1)在指定时长后执行某项操作(2)周期性的执行某项操作
AlarmManager对象配合Intent使用,可以定时的开启一个Activity,发送一个BroadCast,或者开启一个Service.
下面的代码详细的介绍了两种定时方式的使用:
(1)在指定时长后执行某项操作(单次闹钟)
Java代码 复制代码 收藏代码
  1. //操作:发送一个广播,广播接收后Toast提示定时操作完成
  2. Intent intent =new Intent(Main.this, alarmreceiver.class);
  3. intent.setAction("short");
  4. PendingIntent sender=PendingIntent.getBroadcast(Main.this, 0, intent, 0);
  5. //设定一个五秒后的时间
  6. Calendar calendar=Calendar.getInstance();
  7. calendar.setTimeInMillis(System.currentTimeMillis());
  8. calendar.add(Calendar.SECOND, 5);
  9. AlarmManager alarm(AlarmManager)getSystemService(ALARM_SERVICE);
  10. alarm.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),sender);
  11. //或者以下面方式简化
  12. //alarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+5*1000, sender);
  13. Toast.makeText(Main.this, "五秒后alarm开启",Toast.LENGTH_LONG).show();
//操作:发送一个广播,广播接收后Toast提示定时操作完成
Intent intent =new Intent(Main.this, alarmreceiver.class);
intent.setAction("short");
PendingIntent sender=PendingIntent.getBroadcast(Main.this, 0, intent, 0);
//设定一个五秒后的时间
Calendar calendar=Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 5);
    
AlarmManager alarm(AlarmManager)getSystemService(ALARM_SERVICE);
alarm.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),sender);
//或者以下面方式简化
//alarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+5*1000, sender);
    
Toast.makeText(Main.this, "五秒后alarm开启",Toast.LENGTH_LONG).show();

//注意:receiver记得在manifest.xml注册
Java代码 复制代码 收藏代码
  1. public static class alarmreceiver extends BroadcastReceiver{
  2. @Override
  3. public void onReceive(Context context, Intent intent) {
  4. // TODO Auto-generated method stub
  5. if(intent.getAction().equals("short")){
  6. Toast.makeText(context, "short alarm", Toast.LENGTH_LONG).show();
  7. }else{
  8. Toast.makeText(context, "repeating alarm",
  9. Toast.LENGTH_LONG).show();
  10. }
  11. }
  12. }
public static class alarmreceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            if(intent.getAction().equals("short")){
                Toast.makeText(context, "short alarm", Toast.LENGTH_LONG).show();
            }else{
                Toast.makeText(context, "repeating alarm", 
                      Toast.LENGTH_LONG).show();
            }
        }
    }


(2)周期性的执行某项操作(周期性闹钟)
Java代码 复制代码 收藏代码
  1. Intent intent =new Intent(Main.this, alarmreceiver.class);
  2. intent.setAction("repeating");
  3. PendingIntent sender=PendingIntent.getBroadcast(Main.this, 0, intent, 0);
  4. //开始时间
  5. long firstime=SystemClock.elapsedRealtime();
  6. AlarmManager am=(AlarmManager)getSystemService(ALARM_SERVICE);
  7. //5秒一个周期,不停的发送广播
  8. am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,firstime, 5*1000, sender);
Intent intent =new Intent(Main.this, alarmreceiver.class);
intent.setAction("repeating");
PendingIntent sender=PendingIntent.getBroadcast(Main.this, 0, intent, 0);
    
//开始时间
long firstime=SystemClock.elapsedRealtime();
AlarmManager am=(AlarmManager)getSystemService(ALARM_SERVICE);
//5秒一个周期,不停的发送广播
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,firstime, 5*1000, sender);

AlarmManager的setRepeating()相当于TimerSchedule(task,delay,peroid);有点差异的地方时Timer这个方法是指定延迟多长时间
以后开始周期性的执行task;
AlarmManager的取消:(其中需要注意的是取消的Intent必须与启动Intent保持绝对一致才能支持取消AlarmManager)
Java代码 复制代码 收藏代码
  1. Intent intent =new Intent(Main.this, alarmreceiver.class);
  2. intent.setAction("repeating");
  3. PendingIntent sender=PendingIntent.getBroadcast(Main.this, 0, intent, 0);
  4. AlarmManager alarm=(AlarmManager)getSystemService(ALARM_SERVICE);
  5. alarm.cancel(sender);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值