android studio keep device awake

You can keep an Android device awake by using the PowerManager class to acquire a wake lock. Here's a step-by-step guide:

  1. Declare Permission in Manifest: Add the WAKE_LOCK permission to your AndroidManifest.xml file. xml <uses-permission android:name="android.permission.WAKE_LOCK" />

  2. Acquire a Wake Lock: Use the PowerManager to acquire a wake lock in your activity or service. ```kotlin // Inside your Activity or Service val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager val wakeLock = powerManager.newWakeLock( PowerManager.FULL_WAKE_LOCK or PowerManager.ACQUIRE_CAUSES_WAKEUP, "YourTag:WakeLockTag" )

// Acquire the wake lock wakeLock.acquire() ```

  1. Release the Wake Lock: Remember to release the wake lock when it's no longer needed, for instance in onDestroy() or when your app is done using it. kotlin // Release the wake lock if (wakeLock.isHeld) { wakeLock.release() }

Make sure you handle the wake lock lifecycle properly to avoid unnecessary battery drain by releasing the wake lock when it's no longer necessary.