0

I have been trying to figure out how to get the current time in android and I would like to figure how to run a segment of code when the clock hits a certain time. Ultimately what I am trying to do is when the clock is 9:30 pm. Do something or run a piece of code. I have never dealt with time before on android or java.

RedShirt
  • 855
  • 2
  • 20
  • 33

3 Answers3

0

There are various ways you can get the current time in Android such as

Date currentDate = new Date(System.currentTimeMillis());

Regarding running code at a certain time, check out AlarmManager which allows you to schedule a run for your application.

Also, check out Alarm Manager Example

Community
  • 1
  • 1
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
0

There's some things you need to consider when using AlarmManager especially when your device is asleep (acquire a lock, and keep it until your task is completed). I suggest you read that.

mbmc
  • 5,024
  • 5
  • 25
  • 53
0

try this:

get the current system time as below:

long currentTime = System.currentTimeMillis();

and set task for future time as below:

Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
Intent serviceIntent = new Intent(this, GPSTrackerService.class);
PendingIntent pintent = PendingIntent.getService(this, 0, serviceIntent, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
//every 2 min
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),timeSlice, pintent);

for more description refer below link:

How to set an alarm to fire properly at fixed time?

Community
  • 1
  • 1
MohdTausif
  • 498
  • 4
  • 13