The Android operating system allows for the ability to keep certain types of hardware awake through software. One of the most desired features of this is for keeping the screen on. However, often times an application may need to perform a long running task in the background of the phone. For this, Android provides you with something called a wake lock. A wake lock is a feature specific to Android that is provided through something called a power manager. The power manager is a system service that allows you the ability to keep the processor running. In simple terms, this means to prevent the phone from sleeping.
Often times in Android, it is common to perform work with an abstract subclass of the service component. This is called an intent service. You then implement the intent service and override a method named onHandleIntent(). This passes you an intent that was sent from another context optionally containing any data that pertains to the work needed to be performed. All data is passed in the intent’s bundle as extras.
The Android API provides you with an abstract class that inherits from a broadcast receiver component’s implementation. This derived class is named the WakefulBroadcastReceiver in the API. Now, I would like to avoid this as it forces you to have two components instead of one. As a matter of fact, I didn’t even know about this until about 3 minutes ago. And as it turns out it has been deprecated since 8.0 in favor of JobScheduler.
In order to avoid this unnecessary second component, we must create are own wake lock. Let’s start by creating a subclass of IntentService and declaring a member variable of type PowerManager.Wakelock.
The next step is to encompass the work performed within the life span of the wake lock. This is accomplished by initializing and acquiring your wake lock at the top of onHandleIntent and then releasing the wake lock at end of the method. But before we do, it is important to know about the two types of wake locks. One of these two types is passed in as a flag to the operating system to let it know what type of wake lake to acquire for us. The two types are full and partial. However, we will not discuss the differences as full wake lock was deprecated years ago. Therefore, we will instantiate our wake lock with the partial flag.
We must let the operating system know that this service exists by declaring it inside of the manifest.xml file.
Finally, we need to declare the permission that is required to use a wake lock in the manifest.xml file.
Androidx, which replaces the android support library, has recently included an intent service with a wake lock called a JobIntentService. However, it is quite complicated in comparison to my library called WakeService, This additional complexity is the consequence of more features. So, I hope you enjoy my WakeService library and find its’ simplicity useful. Especially, if all you require is a wake lock to wrap your work in.