Android AlarmManager

Android开发中除了使用Timer和TimerTask开发定时任务外,还可以使用系统自带的Alarm服务。之前有比较一下Timer和AlarmManager来刷新界面数字,发现用Timer的休眠了手机后时间会变慢,所以如果要开发时间精准比较高的手机程序还是使用系统自带的AlarmManager吧。

使用AlarmManager一般代码:

        mAlarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        mIntent = new Intent(unique);
        mPendingIntent = PendingIntent.getBroadcast(this, 0, mIntent, 0);
        mAlarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis(), 5 * 1000, mPendingIntent);
        registerReceiver(RefreshReceiver, new IntentFilter(unique)); //动态注册了一个receiver,receiver代码未给出

大多程序都是配合PendingIntent、Intent、BroadcastReceiver使用的。

简单说一下AlarmManager的其他内容:

主要方法:

 
 
        mAlarmManager.set(type, triggerAtTime, operation); //设置一次性闹钟	
        mAlarmManager.setInexactRepeating(type, triggerAtTime, interval, operation); //设置重复闹钟,interval间隔时间是不精确的
        mAlarmManager.setRepeating(type, triggerAtTime, interval, operation); //设置重复闹钟
        mAlarmManager.setTime(millis); //设置系统时间
        mAlarmManager.setTimeZone(timeZone); //设置系统时间时区


重要参数 type, 闹钟类型:

        AlarmManager.ELAPSED_REALTIME; //时间流逝时间,即相对于系统启动时间,睡眠时间考虑在内,睡眠状态不可用
        AlarmManager.ELAPSED_REALTIME_WAKEUP; //时间流逝时间,即相对于系统启动时间,睡眠时间考虑在内,睡眠状态下唤醒
        AlarmManager.RTC; //硬件时间,即系统时间,睡眠状态不可用
        AlarmManager.RTC_WAKEUP; //硬件时间,即系统时间,睡眠状态下唤醒

ELAPSED 和 RTC区别:相对时间和绝对时间的区别,RTC可以通过修改系统时间触发闹钟



你可能感兴趣的:(android,timer,timezone,service,手机)