Time in Milliseconds Alarm
Okay, So I'm working on having an alarm that gives a notification at, lets say 3:00 PM daily, but I want this to be selectable by the user, between AM/PM, and Hours/Min freely changeable. I will probably use a TimePicker
, and this is my code I have so far:
public void startAlarm() {
Intent intent = new Intent(currentDay.this, AlarmReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(currentDay.this,0, intent,0);
long firstTime = SystemClock.elapsedRealtime();
firstTime += 15*1000;
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,firstTime,AlarmManager.INTERVAL_DAY, sender);
}
So, I figure I'm going to be using something along the lines of:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 19);
cal.s开发者_Python百科et(Calendar.MINUTE, 45);
and then using
cal.getTimeInMillis()
But this doesn't work, any ideas? Thanks!
EDIT: So, long story short, I know how to get the current time, then add lets say 15 seconds to it, but I want to have a definite time that WORKS for example 5:14 PM, and everything I've tried doesn't work
As far as I can tell you are getting a Calendar instance with the current date/time and then you are adding 19 hours and 45 minutes to it, NOT setting the time of the Calendar instance explicitly to 19:45. Is that what you are meaning to do? You need to use the Calendar set() method to set an explicit time.
From the API reference for Calendar
Calendar's getInstance method returns a calendar whose locale is based on system settings and whose time fields have been initialized with the current date and time:
Calendar rightNow = Calendar.getInstance()
public abstract void add (int field, int value)
Since: API Level 1
Adds the specified amount to a Calendar field.
Parameters
field the Calendar field to modify.
value the amount to add to the field.
Throws IllegalArgumentException if field is DST_OFFSET or ZONE_OFFSET.
EDIT: To convert local time to UTC...
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 19);
cal.set(Calendar.MINUTE, 45);
int offset = cal.getTimeZone().getOffset(cal.getTimeInMillis());
firstTime = cal.getTimeInMillis() + offset;
NOTE: I haven't tried the above and there may be an easier way but it should work. It's hard for me to test stuff like this as my timezone is GMT/UTC.
精彩评论