-1

I'm trying to implement a service that does some work every second, even when the screen is off.

I have tried using handlers and timertask together with partial wake lock with no luck.

And as far as i know it is not possible to use alarm manager at such low intervals.

How do i achieve this ?

UPDATE

It turned out that all my different timer implementations worked.. After a phone restart, wake lock behaved correctly.

According to isHeld() wake lock was acquired and released correctly, but it behaved as if it was never acquired. Which it probably was not.

p900
  • 1
  • 2
  • 2
    Your question is contradictory. A device wouldn't be "sleeping" (at least not in a very battery-efficient way) if it had an app that was trying to do work every second. What are you really trying to accomplish here? – Doug Stevenson Feb 09 '16 at 23:16
  • Im creating a timer that will be useing intervals rangeing from 1 second to 30 minutes. Feedback is given not only on screen but also as sound and vibration, so it must also work when the device is "sleeping". Yes the app is a battery shark but the user expect that. – p900 Feb 09 '16 at 23:36
  • Well, you can ensure that your app is active on the device 100% of the time if it's not showing an activity on the screen all the time. Android has the right to kill any process any time it needs resources. You can try very hard to stay running by having a Service active in the foreground, and having that Service hold a wake lock to keep the device from sleeping. You could also have the Service be "sticky" so that it may get restarted if Android has to kill it. – Doug Stevenson Feb 09 '16 at 23:48

1 Answers1

0

You need to use CountDownTimer along with wakelock. Refer below:

Class Overview

Schedule a countdown until a time in the future, with regular notifications on intervals along the way. Example of showing a 30 second countdown in a text field:

 new CountDownTimer(30000, 1000) {


 public void onTick(long millisUntilFinished) {
     mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
 }

 public void onFinish() {
     mTextField.setText("done!");
 }   }.start();  

The calls to onTick(long) are synchronized to this object so that one call to onTick(long) won't ever occur before the previous callback is complete. This is only relevant when the implementation of onTick(long) takes an amount of time to execute that is significant compared to the countdown interval.

Please note acquiring wakelock is important otherwise the device might go to sleep.For more info about wakelocks refer-http://developer.android.com/training/scheduling/wakelock.html

rupesh jain
  • 3,410
  • 1
  • 14
  • 22