简体   繁体   中英

Setting the Alarm at specific time of the day

I'am trying to set my alarm at certain time of the day eg: 20:15 and this is the code that i'm working with but it doesn't go off at 20:15

        Intent intent = new Intent(AlarmActivity.this, MyBroadcastReceiver.class);
        intent.putExtra("Hekma", "One better than none");
        PendingIntent pintent = PendingIntent.getService(AlarmActivity.this, 0,intent, 0);
        AlarmManager alarm = (AlarmManager)getSystemService(ALARM_SERVICE);
        Calendar cal = Calendar.getInstance();



        cal.set(Calendar.HOUR_OF_DAY, 20);
        cal.set(Calendar.MINUTE, 15);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        alarm.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pintent);

I use AlarmManager in my project and it works perfectly. Try this it may help you:

Intent myIntent =  new Intent(MainActivity.this, MyAlarmService.class);
pendingIntent = PendingIntent.getService(MainActivity.this, 0, myIntent, 0);
AlarmManager alarmManager =  (AlarmManager) getSystemService(ALARM_SERVICE);

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

Try

alarm.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis() - System.currentTimeMillis(), pintent);

This should get the difference between the two times and therefore how long to go before when you want it to go off. Hence, it should go off at the time you want it to go off.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM