• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Advice needed: Service or Thread?

GIR

Member
Hello,

I am making an app that makes sure someone is safe my monitoring their motion via the accelerometer, but this is draining the battery very quickly.

To help mitigate this I am considering moving the main code to either a service or a thread so the sensors can be used on a 1 minute on/off duty cycle.

Which should I use? Ideally the app should keep monitoring in the background when the screen goes off).

Regards,
GIR
 
I would suggest using a Service, as this will allow you to run it in the background even when your app isn't running.
 
  • Like
Reactions: GIR
In that case I would do as mentioned before, a service but coupled with an Alarm..


1) Create a PendingIntent to invoke your service
2) provide this PendingIntent to the AlarmManager with a repeat time interval
3) inside your service OnStartCommand method , do your one time sensor stuff

part 3) can be a bit more complex depending if you've todo asynchronous stuff , because if initialy your device was in deep sleep it will be wake up by the alarm but may return to sleep before you may do your sensor stuff...
So you may acquire a wakeLock from PowerManager (CPU only (PARTIAL_WAKE_LOCKl) ) then do your sensor stuff and at the end do not forget to release the WakeLock. to allow your device to return to deep sleep and not draining unecessary battery power.

So to resume :
periodicaly Android Alarm Service Invoke your service
Your service request sensor information
all this is done even if screen is off or in deep sleep ..

I guess my method is power respetfull ... I guess i saw this low power usage with alarm service on an Google IO video... can't find right away the ref ...

NB: DeepSleep means CPU is frozen .. all app running are frozen .. low power !


Hope that help

have fun
 
Back
Top