3

I want to develop a sleep tracking app that should work even when device's screen gets off. I'm curious about whether Service or Handler go to sleep when device screen is off. I learned the life-cycle of activity, so I don't think a Handler would work since activities go to sleep when device's screen is off, and Handlers are dependent on its activity. But the Service is a background process, so I think it might work.

So I want the device to be alive even when device's screen is off. Could you give me some advice for this?

Nathan Ernst
  • 4,540
  • 25
  • 38
강신욱
  • 131
  • 1
  • 7

3 Answers3

2

Your application will be paused after a while if device screen is locked. The CPU will sleep until user wakes the device, so, your Service won't do anything while device sleeps.

If you want to perform some action even when the screen is turned off, you can acquire a WakeLock: http://developer.android.com/reference/android/os/PowerManager.WakeLock.html But be careful, using the WakeLock too much will drain battery fast.

Also, another class that may be useful for you is WakefulBroadcastReceiver: https://developer.android.com/reference/android/support/v4/content/WakefulBroadcastReceiver.html

What it does is, it receives some Intent and acquires a WakeLock for you so that you can finish your work in a Service. Without this you have no guarantee that device will finish the work and not go to sleep.

Gennadii Saprykin
  • 4,505
  • 8
  • 31
  • 41
0

Services pause when the screen turns off. This is done to prevent battery draining.
In your case, since you want your service to run for a longer period of time, you can consider using PowerManager.WakeLock
Here is the link.

But you should keep in mind that using WakeLocks might affect the device's battery backup to a great extent.

pri
  • 1,521
  • 2
  • 13
  • 26
  • I don't think that service will keep running for a long time when device's screen is off. Why do we need `startWakefulService ` then? By default there is no wake lock, thus, service will be paused till device is awake. – Gennadii Saprykin Jul 29 '15 at 05:56
-1

does service or handler go to sleep too when device's lcd goes off?

No, Your service will run in to the background all the time until user force stop that service.

If you want your service to live all the time then you need to return START_STICKY to onStartCommand()

dharmendra
  • 7,835
  • 5
  • 38
  • 71