您的位置:首页 > 其它

AlarmManager

2015-08-26 22:58 176 查看
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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: