zoukankan      html  css  js  c++  java
  • android的全局定时器AlarmManager详解


    AlarmManager对象配合Intent使用,可以定时开启一个Activity,发送一个BroadCast或者开启一个Service。

    AlarmManager有如下用法:

    (1)在指定时间后,执行某操作

    1. Intent intent=new Intent(this,ShowUtil.class);  
    2. PendingIntent sender=PendingIntent.getBroadcast(this0, intent, 0);  
    3. AlarmManager alarm=(AlarmManager)getSystemService(ALARM_SERVICE);  
    4. alarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+4*1000, sender);//4秒后执行  
     

    (2)周期性执行某动作

    1. Intent intent=new Intent(this,ShowUtil.class);  
    2. PendingIntent sender=PendingIntent.getBroadcast(this0, intent, 0);  
    3. AlarmManager alarm=(AlarmManager)getSystemService(ALARM_SERVICE);  
    4. alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() 5*1000, sender);//每5秒执行一次  
    5. //alarm.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 5*1000, sender);//每5秒执行一次  
     

    (3)关于同时定义多个定时器和关闭指定定时器

    1. public static PendingIntent sender1;  
    2. public static PendingIntent sender2;  
    3. Intent intent=new Intent(this,ShowUtil.class);  
    4. sender1=PendingIntent.getBroadcast(this1, intent, 0);//第二个参数,用来标识不同的send  
    5. sender2=PendingIntent.getBroadcast(this2, intent, 0);  
    6. AlarmManager alarm=(AlarmManager)getSystemService(ALARM_SERVICE);  
    7. alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 2*1000, sender1);  
    8. alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 5*1000, sender2);  
    9. //在其他地方  
    10. AlarmManager alarm=(AlarmManager)getSystemService(ALARM_SERVICE);  
    11. alarm.cancel(**.sender1);  
    12. alarm.cancel(**.sender2);  
       













  • 相关阅读:
    14_java之变量|参数|返回值|修饰符
    NYOJ 202 红黑树 (二叉树)
    NYOJ 138 找球号(二) (哈希)
    NYOJ 136 等式 (哈希)
    NYOJ 133 子序列 (离散化)
    NYOJ 129 树的判定 (并查集)
    NYOJ 117 求逆序数 (树状数组)
    NYOJ 93 汉诺塔 (数学)
    HDU 2050 折线分割平面 (数学)
    天梯赛L2-008 最长对称子串 (字符串处理)
  • 原文地址:https://www.cnblogs.com/liulaolaiu/p/11744508.html
Copyright © 2011-2022 走看看