AlarmManager的使用记录

warning: 这篇文章距离上次修改已过1582天,其中的内容可能已经有所变动。

这里是方便自己使用和理解记录一下,居然细节百度Google太多了,这里略。
使用需求是在指定时间,执行任务,然后每日进行重复,这里是每日23点为例。

Calendar.getInstance();//先获取到,方便操作时间。
calendar.setTime(new Date()); //给它设置时间
Calendar.HOUR_OF_DAY;//这里是使用24时计时法

  //判断时间是否在23点之后
    if (calendar.get(Calendar.HOUR_OF_DAY) >= 23) {//之后为隔天
        calendar.add(Calendar.DATE, 1);
    }

//指定时间为 23时00分
    calendar.set(Calendar.HOUR_OF_DAY, 23);
    calendar.set(Calendar.MINUTE, 0);//分

//设置可唤醒的时间计时方式,指定唤醒的时间,每隔一天(精确到毫秒),执行的任务
 manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24 * 60 * 60 * 1000, getAlarmPendingIntent());

获取意图,意图为操作记步服务,“PendingIntent.getService”是操作服务,这里可以“PendingIntent.getActivity”操作其他。

 private PendingIntent getAlarmPendingIntent() {
    Intent intent = new Intent(this, StepService.class);
    intent.setAction("alarmSeedNet");
    return PendingIntent.getService(this, 2001, intent, PendingIntent.FLAG_CANCEL_CURRENT);
}

其中服务可以再 onStartCommand 或者onStart中获取意图,推荐在onStartCommand 操作,onStartCommand 优先于onStart,Activity在onCreate,或者其他。

    @Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null && "alarmSeedNet".equals(intent.getAction())) {//发送记录
//            Log.e(TAG, "============== send ====================");
        sendStepToNet();
    }

    return super.onStartCommand(intent, flags, startId);
}

添加新评论

captcha