android 定时任务 Alarm机制

Android中定时任务一般有两种实现方法,一种是使用java API中里提供的Timer类,一种是使用Android的Alarm机制,这两种方式都能实现类似的效果,但Timer有一个明显的短板,它不适合那些需要长期在后代执行的定时任务。我们知道为了让电池更加耐用,手机都会有自己的休眠策略,Android手机就会在长时间不操作的情况下自动让CPU进入休眠状态,就会导致Timer中的定时任务无法正常运行。Alarm机制就不存在这种情况,它具有唤醒CPU的功能,可以保证每次执行定时任务时CPU能正常工作。
1,Alarm机制的用法,它主要就是使用AlaerManager类来实现的,我们通过Context的getService()方法来获取实例,只是这里需要传入的参数Context.ALARM_SERVICE.就可以获得一个AlarmManage的实例。

        AlarmManager systemService = (AlarmManager)getSystemService(ALARM_SERVICE);

2,AlarmManager常用的有三个方法:

//第一个参数是类型,第二个是执行的时间,第三个是执行的动作
systemService .set(int type,long startTime,PendingIntent pi);
//第一个参数是类型,第二个是首次执行时间,第三个是时间间隔,第三个是执行的动作
systemService .setRepeating(int type,long startTime,long intervalTime,PendingIntent pi);
//与第二个方法相似,不过其两个执行的间隔时间不是固定的而已。
systemService .setInexactRepeating(int type,long startTime,long intervalTime,PendingIntent pi);

3,AlarmManager的类型一般有四种:

  • AlarmManager.ELAPSED_REALTIME 表示手机睡眠状态下不可用,该状态下闹钟使用相对时间(相对于系统启动开始);
  • armManager.ELAPSED_REALTIME_WAKEUP 表示睡眠状态下会唤醒系统CPU并执行,该状态下也使用相对时间);
  • AlarmManager.RTC 表示在睡眠状态下不可用,该状态下使用绝对时间,即当前系统时间;
  • AlarmManager.RTC_WAKEUP表示在睡眠状态下会唤醒系统CPU并执行,该状态下使用绝对时间;

4,开启一个服务

Intent intent3 = new Intent(this, LongRunningService.class);
startService(intent3);

5.在Service的OnStartCommand()方法里写入

 public int onStartCommand(Intent intent, int flags, int startId) {
        new Thread(new Runnable() {
            @Override
            public void run() {

            }
        }).start();
           AlarmManager systemService = (AlarmManager) getSystemService(ALARM_SERVICE);
            long anHour = 60 * 60 * 1000;//这是一个小数的毫秒数
            long l = SystemClock.elapsedRealtime() + anHour;
             Intent intent9 = new Intent(this, AlarmReceiver.class);
            PendingIntent broadcast = PendingIntent.getBroadcast(this, 0, intent9, 0);
            systemService.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,l,broadcast);
           return super.onStartCommand(intent, flags, startId);
    }

6.在Thread线程里就可以写入具体的操作,这里我们用到了一个AlarmReceiver广播,在广播里写入:

public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent intent1 = new Intent(context, LongRunningService.class);
        context.startService(intent1);
    }
}

7.就这样服务就会一个每个一个小时就会执行一次,一个在长期在后台定时运行的服务就完成了。另外Android4.4开始,Alarm任务的触发时间将会变的不那吗准,这是因为系统在耗电方面进行了优化,系统会检测到目前有多少个Alarm任务存在,然后将触发的时间相近的几个任务放在一起运行,就可以减少CPU的唤醒次数,从而延长电池寿命.

8.如果想做定时闹钟可以用到下面那两个方法,他是可以保证准确无误的执行。

   Intent intent = new Intent("com");
        intent.putExtra("com","该吃药了");
        PendingIntent pi = PendingIntent.getBroadcast(this,0,intent,0);
        AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
        am.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),10*1000,pi);
       String string = intent.getStringExtra("com");  
        Toast.makeText(context,string ,Toast.LENGTH_SHORT).show();  

记得在广播注册一下:

        <receiver android:name=".AlarmReceiver">
            <intent-filter>
                <action android:name="com"></action>
            </intent-filter>
        </receiver>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值