Open In App

Understanding Wake Locks in Android 13

Improve
Improve
Like Article
Like
Save
Share
Report

You may have come across various instances where you would want to keep the device awake when your app is performing some kind of action or a process so that it doesn’t go in the background and ultimately get killed by the Android System. Android 13 also comes with many improvements under the hood like improved App-Hibernation and various other battery management features that make it almost impossible for your app to carry long battery-intensive tasks.

Thus, arrives the need of getting wake-locks enabled in our Android Application so that our app can continue to work even if the user leaves the device or switches to another app. In this Geeks for Geeks article we will learn how even after Android 13, you can have better control over the overall state of your app.

GeekTip: Some methods discussed in this article also back work with previous Android Versions so you can try implementing them on previous versions as well.

What is Forced Wakeup?

An Android device that is left idle rapidly goes to sleep to prevent battery consumption. The CPU or the screen may occasionally need to be kept awake by an application in order to finish a task. We already know how to keep the screen awake, herein we will look at keeping the CPU awake.

Your strategy will rely on what your app requires. To reduce your app’s impact on system resources, you should utilize the most lightweight approach feasible, according to popular wisdom. The sections that follow explain how to manage situations where your app’s requirements conflict with the device’s standard sleep behavior.

How to keep the CPU awake:

Use wake locks, a PowerManager system service feature, if you need to keep the CPU active so that you can do some tasks before the device goes to sleep. Wake locks provide your program control over the host device’s power state.

The host device’s battery life can be significantly impacted by creating and maintaining wake locks. As a result, you ought to only employ wake-locks when absolutely required and hold them for as little time as feasible. For instance, in an activity, you ought to never need to employ a wake lock.

A background service that has to take a wake lock to keep the CPU running so it can work when the screen is off would be one reasonable use for a wake lock. Again, though, because of the effect it has on battery life, this behavior should be minimized.

To activate CPU Always Awake:

Step 1: Declare the permissions

Like all the other permissions, to do something out of the blue, we need to ask for permission, in a similar way as we obtain permission to obtain wake-lock

<!--Add this Permission to attain WakeLock -->
<uses-permission android:name="android.permission.WAKE_LOCK" />

Image #1: Adding the Wake Lock Permission.

Step 2: Determine the hold of the CPU

You can control your wake lock with a WakefulBroadcastReceiver if your app has a broadcast receiver that utilizes a service to perform some tasks, as explained in Ensure that the broadcast receiver keeps the device awake. We will now look at the code which will hold the CPU for a specific time frame. In this scene, we hold it for 20 minutes. 

The preferred method is this. Following is a straightforward method to set a wake lock if your app doesn’t adhere to that pattern:

Java




import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.PowerManager;
 
public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        acquireWakeLock();
    }
 
    private void acquireWakeLock() {
        //This code holds the CPU
        PowerManager gfgPowerDraw = (PowerManager)getSystemService(POWER_SERVICE);
        PowerManager.WakeLock gfgPowerLatch = gfgPowerDraw.newWakeLock(
                PowerManager.PARTIAL_WAKE_LOCK,
                "GfGApp::AchieveWakeLock");
        gfgPowerLatch.acquire(20*60*1000L); // 20 minutes
    }
}


Image #2: Adding the Wake Lock Code to Hold the CPU.

GeekTip: Call wakelock.release to release the wake lock (). Your claim is now released to the CPU. To prevent battery waste, it’s crucial to release a wake lock as soon as your app is done using it.

With these two simple methods, you can keep the CPU awake for as long as you want, but do note that continuous exploitation of this service may lead to your app getting flagged over the new Foreground Task Manager in Android 13.

An alternative to Keeping CPU Awake:

If keeping the CPU awake causes your app to become part of the heavy battery kill list, then this method will help you avoid it, and still keep your tasks running, the trick is to simply declare a new broadcast, that will keep the purpose working and your app can benefit with that.

Step 1: Creating the Receiver

The first and foremost step is to register a service, use this to do so:

<!-- Declare your app's register here -->
<receiver android:name=".GeeksforGeeksReceiver"
    tools:ignore="WrongManifestParent">
</receiver>

Image #3: Adding the Receiver callback in the application’s manifest.

Step 2: Stopping the Service, when done

The service makes a call to MyWakefulReceiver when it is finished. To release the wake lock, call completeWakefulIntent(). The identical intent that was supplied by the WakefulBroadcastReceiver is the parameter for the completeWakefulIntent() method:

Java




public class GfgIntentWakeLatch extends IntentService {
    // Acquiring a Notification ID
    public static final int NOTIF_ID = 101;
    private NotificationManager notificationManager;
    // Addressing notification builder
    NotificationCompat.Builder gfgBuilder;
     
    public GfgIntentWakeLatch() {
        super("GfgIntentWakeLatch");
    }
 
    @Override protected void onHandleIntent(Intent intent) {
        // Creating extra in Intent, Geeks for Geeks
        Bundle extras = intent.getExtras();
    }
}


Image #4: Adding the Wake Lock and Acquiring the Notification.

With this, your app won’t come in the newly introduced Task Manager, and will also work better, as even when the user kills your app, it can continue to work on its own. Look at the screenshot below to see, that the app has acquired the Wake Lock Permission.

Output:
 

Image #5: Screenshot of the application.

The full project can be found here.

Conclusion

The issue arises when some applications frequently hold CPUs, hold them for a long period without dropping them, or perform excessive/unnecessary network and CPU duties using these methods. Some applications do legitimately need this to function effectively. Hope you learned something new in this Geeks for Geeks article, and you use it to keep your work in check.



Last Updated : 09 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads