Android(Java):AlarmService

AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

        Intent intent =new Intent("com.android.settings.action.REQUEST_POWER_ON"); 

       PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,  intent, PendingIntent.FLAG_CANCEL_CURRENT); 

       am = (AlarmManager) context .getSystemService(Context.ALARM_SERVICE);

        am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, time, pendingIntent);

  1. privatevoid startAlarmService(){
  2. Intent intent =new Intent(this, AlarmServiceBroadcastReceiver.class);
  3. intent.setAction("repeating");
  4. sender=PendingIntent
  5. .getBroadcast(this,0, intent,0);
  6. //开始时间
  7. long firstime=SystemClock.elapsedRealtime();
  8. am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP
  9. , firstime,20*1000, sender);
  10. }

AlarmManager,Timer,Thread区别


在android开发中,经常会用到定时触发某些操作,或者是间隔处理某件事

如闹钟,和后台定时请求数据:

需要定时处理闹钟任务

定时向服务器请求数据等

对于上述问题,我们可以通过定时器来完成,普遍的做法使用一个Thread来操作.也有使用Time实现定时操作

而android库里面也有一种全新的操作方式AlarmManager

那这几种方式有何区别呢

1.Thread:使用线程方式

2.Time是java的特性

3.AlarmManager:AlarmManager将应用与服务分割开来后,使得应用程序开发者不用 关心具体的服务,而是直接通过AlarmManager来使用这种服务。这也许就是客户/服务模式的好处吧。

第一种和第二种就不过多解释了,在此着重解释一下第三种

当我们在开发android程序时,有些用户会使用service来管理一些后台的任务,如网络操作,或者间断处理数据等,这些用户需要在用户关闭程序,或者关闭屏幕后也能处理后台任务,可android手机为了节省电池使用,当用户关闭屏幕后,会将cpu置于休眠状态,当休眠状态启动,我们的服务就处于暂停状态了.为了斛决这个问题,android库里就提供了一个AlarmManager的库,AlarmManager是客户/服务模式的模式,也就是说AlarmManager是由系统来管理,而不是我们应用程序的一部分,也就是说AlarmManager是全局的,当我们的程序启用AlarmManager后,就给系统注册了一个服务,该服务会根据你设置的参数定时的向你的应用程序发送消息(注意,此消息以广播方式发送).

AlarmManager的使用如下:

[java] view plain copy
  1. privatevoid startAlarmService(){
  2. Intent intent =new Intent(this, AlarmServiceBroadcastReceiver.class);
  3. intent.setAction("repeating");
  4. sender=PendingIntent
  5. .getBroadcast(this,0, intent,0);
  6. //开始时间
  7. long firstime=SystemClock.elapsedRealtime();
  8. am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP
  9. , firstime,20*1000, sender);
  1. 当系统进入睡眠状态时,这种类型的闹铃不会唤醒系统。直到系统下次被唤醒才传递它,该闹铃所用的时间是相对时间,是从系统启动后开始计时的,包括睡眠时 间,可以通过调用SystemClock.elapsedRealtime()获得。系统值是3    (0x00000003)。
  2. publicstatic final int ELAPSED_REALTIME_WAKEUP
  3. //能唤醒系统,用法同ELAPSED_REALTIME,系统值是2 (0x00000002) 。
  4. publicstatic final int RTC
  5. //当系统进入睡眠状态时,这种类型的闹铃不会唤醒系统。直到系统下次被唤醒才传递它,该闹铃所用的时间是绝对时间,所用时间是UTC时间,可以通过调用 System.currentTimeMillis()获得。系统值是1 (0x00000001) 。
  6. publicstatic final int RTC_WAKEUP
  7. //能唤醒系统,用法同RTC类型,系统值为 0 (0x00000000) 。
  8. Public staticfinal int POWER_OFF_WAKEUP
  9. //能唤醒系统,它是一种关机闹铃,就是说设备在关机状态下也可以唤醒系统,所以我们把它称之为关机闹铃。使用方法同RTC类型,系统值为4(0x00000004)。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值