AlarmManager

AlarmManager闹钟的设置
可以作为一个特定的时间去触发一个事件
三件事;
1、 建立一接收者
receiver,在onreceiver里面写触发
/**
 * 闹铃接受者,时间到了会触发notification的服务
 * @author Administrator
 *
 */
public class AlarmReceiver extends BroadcastReceiver {
 @Override
 public void onReceive(Context context, Intent arg1) {
      //开启消息推送的功能
      Intent service = new Intent(context, MessageNotifactionService.class);
      context.startService(service);
 }
}


2、在manifest里面 注册接受者
<!-- 闹铃定时的接受者 -->
        <receiver android:name="com.wc.xph.receiver.AlarmReceiver">
            </receiver>

3、在程序开启的时候就执行闹铃设置
/**
  * 闹铃的方法,设置18.30分的推送
  */
 private void startAlarm(){
  Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);  
  PendingIntent sender = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);  

  long firstTime = SystemClock.elapsedRealtime(); // 开机之后到现在的运行时间(包括睡眠时间)  
  long systemTime = System.currentTimeMillis();  

  Calendar calendar = Calendar.getInstance();  
  calendar.setTimeInMillis(System.currentTimeMillis());  
  // 这里时区需要设置一下,不然会有8个小时的时间差  
  calendar.setTimeZone(TimeZone.getTimeZone("GMT+8"));  
  calendar.set(Calendar.HOUR_OF_DAY, 18);    
  calendar.set(Calendar.MINUTE, 0);
  calendar.set(Calendar.SECOND, 0);  
  calendar.set(Calendar.MILLISECOND, 0);  
  // 选择的定时时间  
  long selectTime = calendar.getTimeInMillis();  
  // 如果当前时间大于设置的时间,那么就从第二天的设定时间开始  
  if(systemTime > selectTime) {    
   calendar.add(Calendar.DAY_OF_MONTH, 1);
   selectTime = calendar.getTimeInMillis();  
  }
  // 计算现在时间到设定时间的时间差  
  long time = selectTime - systemTime;  
  firstTime = firstTime + time;
  // 进行闹铃注册  
  AlarmManager manager = (AlarmManager)getSystemService(ALARM_SERVICE);  
   manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,  
    firstTime, DAY, sender);  
 }
//24小时
 public static final long DAY = 1000L * 60 * 60 * 24;



在设置了定时达额时候还要在不需要的时候需要取消这个定时的绑定任务,取消这个闹铃定时的任务是通过以下的方式来进行取消的
Intent intent = new Intent("cn.pocketdigi.update.alarm"); 
intent.setClass(this, AlarmReceiver.class); 
PendingIntent pi=PendingIntent.getBroadcast(this, 0, intent,0); 
AlarmManager alarm=(AlarmManager)getSystemService(ALARM_SERVICE); 
alarm.cancel(pi); 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wyu-jat

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值