Is it possible to have several locks to wake up?

I am developing a small application that scans 2D barcodes and then sends each barcode to an IntentService, where a longer task is performed.

When an action is displayed, it should prevent the device from sleeping until the barcode is processed in the service. If the service completes processing, it stops itself, but activity should still be visible.

I want SCREEN_DIM_WAKE_LOCK WakeLock to be enabled during the activity lifecycle, but since this type does not prevent the processor from sleeping, I also need to get PARTIAL_WAKE_LOCK in activity when scanning a new 2D code, and release it in the intent service after processing it.

The purpose of SCREEN_DIM_WAKE_LOCK is to avoid the inconvenience of the user pressing the power button every few seconds to wake the device and read a new barcode. The user will have to read a large number of codes one after another, and activity should be even for short intervals when there is no interaction with the user.

I know that in Android there is no 100% guarantee that the application is on top and not closed, or in the foreground due to several conditions that my application cannot control, but I would like as far as possible.

So you can hold multiple WakeLocks? Where can they be declared as accessible by both activity and service? (Singleton, application extension?)

+6
source share
1 answer

You can hold several WakeLocks. In fact, it was executed all the time when several applications are synchronized simultaneously, when the screen is off. (Imagine that the synchronization of your GMail and Facebook applications occurs simultaneously when the screen is locked. They do not know about each other, they will have different WakeLocks. Perhaps these can be different types of WakeLocks)

Android ensures that all expectations are met (maximum battery drain in other words.)

In my opinion, I think you are thinking too much that you need SCREEN_DIM_WAKE_LOCK, as this can accidentally drain a lot of battery, but I may be mistaken depending on your use case.

So the short answer is YES. You can hold several WakeLocks, and Android will (should) act as expected. The only thing to keep in mind is that you correctly release both Wakelocks.

In the question of getting on top of the screen, I think that you should release WakeLock of your activity when it enters the "Suspended" state (when some other activity is on top or is used intentionally press the power button). Because at the moment, the user is interacting with another application, and you must respect him and let him control his behavior. You do not need to refuse to partially block your service until you are done.

Hope this helps.

+9
source

Source: https://habr.com/ru/post/925654/


All Articles