Use the Android Alarm Manager to set the alarm at the set time

Asked 2 years ago, Updated 2 years ago, 133 views

//alarmBtn.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {

               Intent intent = new Intent(DialogActivity3.this, AlarmDialogActivity.class);
               PendingIntent pIntent = PendingIntent.getActivity(DialogActivity3.this, 0, intent, 0);
               // Start the first alarm
               alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 4500, pIntent);

           }
       });
   }

If you press the button, you can see other activities that you set up 4.5 seconds later.

If you set the time with a timepicker or something... I want to make the alarm go off at that time because it is linked to the cell phone time.

Can I use the setTimeZone function?

Or is it another way?

Even if you google and look at the example, there's nothing that actually sets the time to ring at that time.

android alarm application

2022-09-21 16:42

1 Answers

The second parameter of the AlarmManager.set() function is the time when the alarm is triggered. For example, if you want the alarm to be triggered at 8 a.m. on September 1, 2016, you can add the following from the code you wrote:

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 2016);
calendar.set(Calendar.MONTH, Calendar.SEPTEMBER);
calendar.set(Calendar.DATE, 1);
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);

alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pIntent);

In the example above, the alarm time is set directly by Calendar, but it is not difficult to implement the function you want to create by setting the time by yourself using TimePicker and adding only the part that brings the set time.

For battery efficiency from API 19, the AlarmManager.set() function may not operate the alarm at the correct time. If an accurate alarm is required, use the setExact() function in API 19 and above. Refer to the set() function section on the page below for related information.


2022-09-21 16:42

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.