简体   繁体   中英

AlarmManager Android SDK

I have a problem executing the following code:

            Intent myIntent = new Intent(MedicineEntry.this, DisplaySchedule.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(MedicineEntry.this, 0, myIntent, PendingIntent.FLAG_CANCEL_CURRENT);
            AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, 17);
            calendar.set(Calendar.MINUTE, 25);
            calendar.set(Calendar.SECOND, 0);
            calendar.setTimeInMillis(System.currentTimeMillis());
            calendar.add(Calendar.SECOND, 1);
            alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
            Toast.makeText(MedicineEntry.this, "Alarm Will Start In A Second", Toast.LENGTH_LONG).show();
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_FIFTEEN_MINUTES, pendingIntent);

To elucidate my problem, the app should fire up according to the values set for HOUR_OF_DAY, MINUTE and SECOND - even if the device is in sleep mode. I've tried testing the code, but the app does not seem to work. I've tried replacing AlarmManager.INTERVAL_FIFTEEN_MINUTES with 5*1000 which worked fine. Please go easy with the terminologies. I've just started to program with Android this semester at college.

EDIT: This app I am creating is a 'reminder' app. The user is expected to enter the time which the app should execute.

There are basically two ways of interacting with the AlarmManager. Your post is somewhat vague about which will suit your needs.

Anyway, if you want an "Do every 15 minutes" type of alarm, use the ELAPSED mode:

long firstActivation = SystemClock.elapsedRealtime(); // and not System.currentTimeMillis()
mgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstActivation, INTERVAL_MILLISECS, intent); 

But, if you're looking for an "Do every day at 15:30" semantics, use RTC mode, like this:

  long activationTime = calendar.getTimeInMillis();
  long TWENTY_FOUR_HRS = 24 * 60 * 60* 1000;
  mgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, activationTime, TWENTY_FOUR_HRS, intent);


Two things to note at the above code:

A. I am using a waking up type of alarms. These are potentially expensive as they would wake up a sleeping device. Are you sure this is what you need (hint: most apps do not)?

B. I am using setInexactRepeating() instead of setRepeating() so to allow the alarm manager to batch together several alarms thus saving resources. If you do not have a good reason not to do so, stick to using setInexactRepeating()

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