定时器(Alarmmanager)立即在上午12点 - 凌晨12点59分(00:00-00:59)启动

时间:2012-05-30 08:34:34

标签: android calendar alarmmanager timepicker

我的应用程序旨在在特定时间启动服务。

我使用 timePicker 来接收时间

 time.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {

        public void onTimeChanged(TimePicker view, int hourOfDay, int min) {
            hour = hourOfDay;
            minute = min;
        }
    });

您可以按一个按钮激活闹钟管理器。然后意图应该在此时开始。

public void onClick(View v) {
            cal = Calendar.getInstance();
            int _hour = hour;
            int tmpHour = cal.get(Calendar.HOUR_OF_DAY);
            int tmpMinute = cal.get(Calendar.MINUTE);
            // Alarm is today?
            if (hour > tmpHour || (tmpHour == hour && tmpMinute < minute)){

                tmpHour *= 60;
                _hour *= 60;
            }
            **// Add 24Hours to get difference.
            else {

                tmpHour *= 60;
                _hour *= (_hour + 24) * 60;
            }**
            int minutesToAdd = (_hour + minute) - (tmpHour + tmpMinute);
            Log.d("AlarmExample", "Need to add " + minutesToAdd + " minutes");
            cal.add(Calendar.MINUTE, minutesToAdd);


            cal.set(Calendar.SECOND, 0);
            cal.set(Calendar.MILLISECOND, 0);

...

//alarmmanager

            AlarmManager amanag = (AlarmManager) getSystemService(ALARM_SERVICE);
            amanag .set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);

我有一个问题: 当您选择上午12:00至上午12:59之间的时间时, _hour * =(_小时+24)* 60; 会在您触摸按钮时立即启动闹钟。

我尝试将其更改为_hour =(_ hour + 24)* 60; *但它无效。

你知道如何使这个可靠吗?

诚恳, Wolfen的

1 个答案:

答案 0 :(得分:0)

AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);     

    Intent intent = new Intent(this, OnAlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, 0);               
    Calendar timeOff = Calendar.getInstance();  
//time 12.19AM
    timeOff.set(Calendar.HOUR_OF_DAY, 0);
    timeOff.set(Calendar.MINUTE, 19);
    timeOff.set(Calendar.SECOND, 0);      


 alarmMgr.set(AlarmManager.RTC, timeOff.getTimeInMillis(), pendingIntent);

我使用onAlermReciver实现Broadcast reciver将其设置为intent,然后警报响起OnAlermReciver,它适用于我 你可以用

 alarmMgr.set(AlarmManager.RTC, timeOff.getTimeInMillis(), sender);