3

I have been using Timer & TimerTask with Pseudocode:-

 samplingTask = new TimerTask() {

   public void run() {
     collectSample();
   }

 };

 timer.schedule(samplingTask, 60*1000, 60*1000); //1 min

This application is a long running app (e.g. say 15 minutes without wakelock, and the screen turned off). After scheduling this task, I lock the screen and the phone is in motion (with sensor manager activated for accelerometer). So, ideally this task should run every minute. However, in the logs, I see that the scheduled timer was run at 5th minute, 9th minute and 12th minute only.

FINER: (13,Timer-0,Workout)In Timertask, nth minute=5
FINER: (13,Timer-0,Workout)In Timertask, nth minute=9
FINER: (13,Timer-0,Workout)In Timertask, nth minute=12

My requirement has time-critical sampling with an acceptable delay range of few seconds (1-5 seconds).It appears that if the device is in sleep mode, timer doesn't wake it up and run the scheduled task. Is there any other alternative to this. Documentation says AlarmManager and Handler can be used. I think AlarmManager should ideally be used to do a single shot task based on some system alarm. Is there something I am missing or some alternative to achieve this functionality.

Robin
  • 497
  • 5
  • 19

1 Answers1

0

You can use AlarmManager - it has opportunity to weak up device and run some task repeatedly.

I don't know exactly, but suppose, when user switches off the screen all tasks paused and can't do any code, while device sleep.

Jin35
  • 8,602
  • 3
  • 32
  • 52